【发布时间】:2020-01-14 11:56:15
【问题描述】:
我正在公开一个关于新 API 的视图,并且想知道如何为属性设置默认值,并从我的 appsettings.json 文件中读取它。我该怎么做?
我尝试在视图上使用依赖注入,但这似乎是不可能的,因为它是实例化类的框架。
public class FilteringRequest
{
private readonly IAppContext appContext;
public FilteringRequest(IAppContext appContext)
{
this.appContext = appContext;
}
// TODO: appsettings?
// Perhaps something like appContext.DefaultType
public string Type { get; set; } = "top_rated";
// ...
}
这种方法不起作用,因为我相信框架需要一个无参数的默认构造函数。
An unhandled exception occurred while processing the request.
InvalidOperationException: Could not create an instance of type 'Wanderlust.API.Models.Requests.FilteringRequest'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'request' parameter a non-null default value.
Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
请记住,IAppContext 已经拥有 appsettings.json 文件中定义的所有属性。
【问题讨论】:
标签: c# asp.net-core default-value