从 appsettings.json 到选项的绑定部分
Binding section from appsettings.json to options
所以我试图按照 Microsoft 文档进行操作,Options pattern in ASP.NET Core 但是对于我来说,我似乎无法正确地将“AppSettings”部分作为一个选项添加到我的 AppSettings 对象中。 Configuration.GetSection("应用设置");正在为我返回 null
appsettings.Development.json
{
"AppSettings": {
"Secret": "DEVELOPMENTTOKENTEST"
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Enrich": [ "FromLogContext", "WithMachineName" ],
"Properties": {
"Application": "Oasis.API"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/api_.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 1
}
}
]
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=JS-PC;Initial Catalog=Oasis;Integrated Security=True"
}
}
Class 我的 AppSettings 部分。
public class AppSettings
{
public string Secret { get; set; }
}
我如何尝试阅读该部分并将其配置为依赖注入以用于服务。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// Configure API secret
var test = Configuration.GetSection("AppSettings"); // null... oh?
services.Configure<AppSettings>(con => Configuration.GetSection("AppSettings").Bind(con));
// Swagger generation
services.AddSwaggerGen();
// Database and Repositories
ConfigureRepositories(services);
// Register Services
ConfigureServiceClasses(services);
}
以下是我如何设置它以在我的服务中使用 IOptions。
WebUserService.cs
public class WebUserService : IWebUserService
{
private readonly ILogger<WebUserService> _logger;
private readonly IWebUserRepository _webUserRepository;
private readonly AppSettings _appSettings;
public WebUserService(ILogger<WebUserService> logger, IWebUserRepository webUserRepository, IOptions<AppSettings> appSettings)
{
_logger = logger;
_webUserRepository = webUserRepository;
_appSettings = appSettings.Value;
}
}
你不需要 setup.Its 实现将由 DI 注入 system.You 可以使用以下方法获取 Secret
:
using Microsoft.Extensions.Configuration;
//....
private readonly IConfiguration _mySettings;
public HomeController(IConfiguration mySettings)
{
_mySettings = mySettings;
}
public IActionResult Index()
{
var result = _mySettings.GetValue<string>("AppSettings:Secret");
//...
}
测试结果:
顺便说一句,如果你想注入它,你可以使用下面的代码。
//...
var settingsSection =Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(settingsSection);
在控制器中:
private readonly IConfiguration _mySettings;
private readonly AppSettings _settings;
public HomeController(IOptions<AppSettings> settingsAccessor, IConfiguration mySettings)
{
_mySettings = mySettings;
_settings = settingsAccessor.Value;
}
public IActionResult Index()
{
var vm = new AppSettings
{
Secret= _settings.Secret
};
var result = _mySettings.GetValue<string>("AppSettings:Secret");
}
测试结果:
参考这个.
所以我试图按照 Microsoft 文档进行操作,Options pattern in ASP.NET Core 但是对于我来说,我似乎无法正确地将“AppSettings”部分作为一个选项添加到我的 AppSettings 对象中。 Configuration.GetSection("应用设置");正在为我返回 null
appsettings.Development.json
{
"AppSettings": {
"Secret": "DEVELOPMENTTOKENTEST"
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Enrich": [ "FromLogContext", "WithMachineName" ],
"Properties": {
"Application": "Oasis.API"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/api_.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 1
}
}
]
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=JS-PC;Initial Catalog=Oasis;Integrated Security=True"
}
}
Class 我的 AppSettings 部分。
public class AppSettings
{
public string Secret { get; set; }
}
我如何尝试阅读该部分并将其配置为依赖注入以用于服务。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// Configure API secret
var test = Configuration.GetSection("AppSettings"); // null... oh?
services.Configure<AppSettings>(con => Configuration.GetSection("AppSettings").Bind(con));
// Swagger generation
services.AddSwaggerGen();
// Database and Repositories
ConfigureRepositories(services);
// Register Services
ConfigureServiceClasses(services);
}
以下是我如何设置它以在我的服务中使用 IOptions。
WebUserService.cs
public class WebUserService : IWebUserService
{
private readonly ILogger<WebUserService> _logger;
private readonly IWebUserRepository _webUserRepository;
private readonly AppSettings _appSettings;
public WebUserService(ILogger<WebUserService> logger, IWebUserRepository webUserRepository, IOptions<AppSettings> appSettings)
{
_logger = logger;
_webUserRepository = webUserRepository;
_appSettings = appSettings.Value;
}
}
你不需要 setup.Its 实现将由 DI 注入 system.You 可以使用以下方法获取 Secret
:
using Microsoft.Extensions.Configuration;
//....
private readonly IConfiguration _mySettings;
public HomeController(IConfiguration mySettings)
{
_mySettings = mySettings;
}
public IActionResult Index()
{
var result = _mySettings.GetValue<string>("AppSettings:Secret");
//...
}
测试结果:
顺便说一句,如果你想注入它,你可以使用下面的代码。
//...
var settingsSection =Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(settingsSection);
在控制器中:
private readonly IConfiguration _mySettings;
private readonly AppSettings _settings;
public HomeController(IOptions<AppSettings> settingsAccessor, IConfiguration mySettings)
{
_mySettings = mySettings;
_settings = settingsAccessor.Value;
}
public IActionResult Index()
{
var vm = new AppSettings
{
Secret= _settings.Secret
};
var result = _mySettings.GetValue<string>("AppSettings:Secret");
}
测试结果:
参考这个