问题描述
如何在由 .NET Core 3 框架实例化的模型上为属性设置默认值,从我的 appsettings.json 文件中读取它?
How can I set a default value to a property, reading it from my appsettings.json file, on a model that is instantiated by the .NET Core 3 framework?
我创建了一个 repo(一个全新的 .NET Core 3 项目),我试图说明这个问题:https://github.com/NelsonPRSousa/dependency-injection-default-constructor
I've created a repo (a completely new .NET Core 3 project) where I try to illustrate the problem: https://github.com/NelsonPRSousa/dependency-injection-default-constructor
API 操作:
[HttpGet]
public IEnumerable<WeatherForecast> Get([FromQuery] FilteringRequestModel request)
{
var defaultType = request.Type;
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
型号:
public class FilteringRequestModel
{
/* Please note that we must have a parameterless constructor, since it's the framework responsability to instatiate this object
* when invoking this action: IEnumerable<WeatherForecast> Get([FromQuery] FilteringRequestModel request)
*/
public FilteringRequestModel()
{
//Type = System.Configuration.ConfigurationManager.AppSettings["DefaultTypeTopRated"];
}
public string Type { get; set; } = "top_rated"; // TODO: Read from appsettings
}
推荐答案
你可以使用 IOptions 和依赖注入
You could use IOptions with Dependecy Injection
更新FilteringRequestModel
类
public class FilteringRequestModel
{
public FilteringRequestModel()
{
}
public void Initialize(IOptions<FilteringRequestSettings> settings)
{
if (string.IsNullOrEmpty(this.Type))
{
this.Type = settings.Value.Type;
}
}
public string Type { get; set; }
}
添加一个FilteringRequestSettings
类
public class FilteringRequestSettings
{
public string Type { get; set; }
}
像这样更新appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"FilteringRequest": {
"Type": "foo"
}
}
像这样更新Startup
类中的ConfigureServices
方法
public void ConfigureServices(IServiceCollection services)
{
services.Configure<FilteringRequestSettings>(this.Configuration.GetSection("FilteringRequest"));
services.AddControllers();
}
最后,像这样更新WeatherForecastController
类
[HttpGet]
public IEnumerable<WeatherForecast> Get([FromQuery] FilteringRequestModel request)
{
request.Initialize(_settings);
var defaultType = request.Type;
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
说明
- 您将从 appsettings 加载参数到
IOptions
IOptions
将被注入WeatherForecastController
- 然后您将调用
Initialize
方法您的request
带有IOptions
的参数 Initialize
方法验证是否尚未设置Type
属性(来自查询/请求).如果没有,它将使用 appsettings 中的值(通过IOptions
- You will load parameter from appsettings into
IOptions<FilteringRequestSettings>
IOptions<FilteringRequestSettings>
will be injected intoWeatherForecastController
- You will then call the
Initialize
method yourrequest
parameter withIOptions<FilteringRequestSettings>
- The
Initialize
method verify if theType
property has not already been set (from query / request). If not, it will use the value from appsettings (throughIOptions<FilteringRequestSettings>
这篇关于如何将 appsettings 中的默认值设置为 API 模型上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!