c# - ASP.NET Core 2 中的问题配置选项

标签 c# asp.net-core asp.net-core-2.1

在我的项目上配置选项时,我遇到了这个错误:

System.InvalidOperationException: Could not create an instance of type 'Microsoft.Extensions.Options.IOptions`1[[myproject.Models.ConnectionStrings, ]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'optionsAccessor' parameter a non-null default value.



任何的想法 ?

我将模型配置如下:
namespace myproject.Models
{
  public class ConnectionStrings
  {
    public ConnectionStrings()
    {
        AzureStorageConnectionString = "azurestorageconnectionstring_ctor";
    }
    public string AzureStorageConnectionString { get; set; }
  }
}

Startup.cs ConfigureServices(IServiceCollection services) 包含以下两行
services.AddOptions();
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

我的 Controller 包含这个
private ConnectionStrings _connectionStrings;
public IActionResult Index(IOptions<ConnectionStrings> optionsAccessor)
{
  _connectionStrings = optionsAccessor.Value;
  return View();
}

我的 appsettings.json 和 appsettings.Development.json 都包含以下
{
 "Logging": {
 "LogLevel": {
   "Default": "Debug",
   "System": "Information",
   "Microsoft": "Information"
  }
 },
 "ConnectionStrings": {
   "AzureStorageConnectionString": "xxxxxxxxx"
 },
}

最佳答案

你应该注入(inject) IOptions<ConnectionStrings>进入 Controller 的构造函数,而不是进入 Index()方法。

通过将其定义为操作参数,您期望 ModelBinder为您构建它(显然,它不能)。

Documentation

关于c# - ASP.NET Core 2 中的问题配置选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52708409/

相关文章:

c# - Azure Maps 批量地理编码状态 202 12 小时以上

asp.net-core - 区域链接不会在 asp.net-core-mvc 中生成

c# - 一个 Controller 的基于角色的授权重定向 URL

visual-studio - 在 VS 中为 ASPNETCORE_URLS 配置多个 url 应该使用哪个分隔符?

javascript - ASP.NET Razor Pages JavaScript 文件返回未定义的错误

c# - asp.net 列表框更新

c# - 选择 jquery 对话框时如何停止重新加载 asp.net 页面?

asp.net-mvc - ASP.NET核心2 : how to RedirectToPage with area?

c# - 同步调用第三方异步任务方法

c# - EF Core - System.InvalidOperationException : ExecuteReader requires an open and available Connection. 连接的当前状态已关闭