在我的项目上配置选项时,我遇到了这个错误:
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/