ASP.NET 核心 2 : Model bound complex types must not be abstract or value types and must have a parameterless constructor

标签 asp.net asp.net-core

我想使用 IOptions 通过 POCO 获取配置,但它会抛出错误消息“模型绑定(bind)的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数”

DatabaseSettings.cs

public class DatabaseSettings
    {
        public string MongoDBServer { get; set; }
    }

appsettings.json

"DatabaseSettings": {
    "MongoDBServer": "localhost"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc();
      services.Configure<DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
}

Controller

public IActionResult Create(IOptions<DatabaseSettings> options)
{
  string test = options.Value.MongoDBServer;
  return View();
}

我不知道怎么办。你有什么建议给我吗?谢谢!

最佳答案

我遇到了同样的问题。我找到了 this回答很有帮助。

请尝试将 [FromServices] 添加到 Controller 操作:

public IActionResult Create([FromServices] IOptions<DatabaseSettings> options)

关于ASP.NET 核心 2 : Model bound complex types must not be abstract or value types and must have a parameterless constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029367/

相关文章:

c# - Blazor 服务器端 InputSelect 为字节数据类型,onChange 事件错误

c# - 如何手动取消 ASP.net 核心中的 BackgroundService

c# - ASP.NET MVC 4 Controller 失败找不到与名为 'account' 的 Controller 匹配的类型

asp.net-core - SignalR:无法在 Visual Studio 2017 项目中获取 js 库

c# - 自托管 ASP.NET Web API 和自托管 SignalR 一起 Windows 服务应用程序

c# - 用现有的数据库信息替换默认的 IdentityDbContext

c# - 如何将 Kestrel 配置为使用随机动态端口并在 ASP.NET Core 3.1 运行时确定端口?

asp.net-core - 在 ASP.NET 5/MVC 6 中检索到 Azure 存储的连接字符串

asp.net - 处理 TextBox 中的 ENTER 按钮,ASP.NET

asp.net - 从数据库中获取 NULL 值并分配给 Date 变量