所以我试图遵循 Microsoft 文档,Options pattern in ASP.NET Core然而,对于我的一生,我似乎无法正确地将“AppSettings”部分作为一个选项添加到我的 AppSettings 对象中。 Configuration.GetSection("AppSettings");正在为我返回 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"
}
}
我的 AppSettings 部分的类。
public class AppSettings
{
public string Secret { get; set; }
}
我如何尝试阅读该部分并将其配置为依赖注入(inject)以用于服务。
启动.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;
}
}
最佳答案
你不需要设置。它的实现将由DI系统注入(inject)。你可以使用下面的方法来获取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");
//...
}
顺便说一句,如果你想注入(inject)它,你可以使用下面的代码。
//...
var settingsSection =Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(settingsSection);
在 Controller 中:
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");
}
引用这个thread .
关于c# - 从 appsettings.json 到选项的绑定(bind)部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65757814/