c# - 从 appsettings.json 到选项的绑定(bind)部分

标签 c# asp.net-core asp.net-core-3.1 appsettings

所以我试图遵循 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;
        }
}

enter image description here

最佳答案

你不需要设置。它的实现将由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");
        //...
    }

测试结果: enter image description here

顺便说一句,如果你想注入(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");
    }

测试结果: enter image description here

引用这个thread .

关于c# - 从 appsettings.json 到选项的绑定(bind)部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65757814/

相关文章:

c# - 在 C# 中使用 OLEDB 连接读取 Excel 文件

C#:根据平台访问 32 位/64 位 DLL

c# - .NET Core 2.0 分离 Startup.cs 服务注入(inject)

azure - 通过应用服务节省 Azure 计费成本?

.net - 为什么 ASP.NET Core Web 应用程序中有 Main() 方法(入口方法)?这种方法背后的原因是什么?

c# - 带有 JWT token 的 Azure AD Multi-Tenancy 、.Net Core Web API

c# - .Net core 3.1 版本如何使用WCF服务编程

c# - 检查数据库是否已经有一个日期时间等于表单中传递的日期时间

c# - 带有异步 lambda 和 Task.WaitAll 的 Task.Factory.StartNew

c# - 使用 asp.net core 2.2 恢复 nuget 包时出现问题