c# - 尝试使用启动文件中的 GetSection 访问它们时,配置值为空。(IOptions-config 检索)

标签 c# asp.net-core dependency-injection config

我无法从 .NET Core 中的 appsettings 文件接收配置值。

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "PortedConfig": {
    "ConfigTableAccess": "ConfigTableConnectionString",
    "ConfigTableName": "Config"
  }
}

startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    var config = Configuration;
    var settings = Configuration.GetSection("PortedConfig").Get<PortedConfig>();
    services.Configure<PortedConfig>(options => Configuration.GetSection("PortedConfig").Bind(options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddScoped<IEncryptManager, EncryptManager>()
            .AddScoped<IDecryptManager, DecryptManager>();
}

PortedConfig.cs:

public class PortedConfig
{
    public string ConfigTableAccess;
    public string ConfigTableName;
}

startup.cs 中,在运行时配置被填充,但是当我使用 GetSection 时,值为空,如下图所示:

Screenshot of Configuration Screenshot of Configuration

如上图所示,ConfigTableAccessConfigTableName 在设置变量中为空。

最佳答案

将字段更改为属性,不要忘记公共(public) setter 。

public class PortedConfig
{
    public string ConfigTableAccess { get; set; }
    public string ConfigTableName { get; set; }
}

关于c# - 尝试使用启动文件中的 GetSection 访问它们时,配置值为空。(IOptions-config 检索),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249653/

相关文章:

c# - 从派生类内部调用 C# 基类扩展方法?

asp.net-core - 使用 OpenCover 运行 XUnit 和 FluentAssertions 会出现错误消息

ajax - 如何在 Asp.Net Core 中创建 AJAX 表单

java - 泛型类型的injector.getInstance

scala - 使用 Guice 注入(inject) Akka Actor 来玩 Framework 2.5 失败

c# - 我应该选择什么样的设计原则/模式?

c# - netstandard - 正则表达式,无法访问组名

c# - 使用依赖注入(inject)注入(inject)多个实现

c# - UNITY-仅更改 3D 模型颜色的某些部分

.net - VS 2017 (.net core) 中的 Nuget 包安装失败