繁体   English   中英

Configuration.GetSection 总是返回 Value 属性 null

[英]Configuration.GetSection always returns Value property null

每次调用Configuration.GetSection ,返回对象的Value属性始终为 null。

我的Startup构造函数

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    this.Configuration = builder.Build();
}

我的ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SqliteSettings>(opts => Configuration.GetSection("SqliteSettings").Bind(opts));

    services.AddOptions();

    services.AddMvc();
}

我的appsettings.json

{
  "SqliteSettings": {
    "DataSource": "C:\\db.sqlite",
    "NewDatabase": true,
    "Version": 3
  }
}

我用来定义 SqliteSettings 的类

public class SqliteSettings
{
    public string DataSource { get; set; }

    public bool? NewDatabase { get; set; }

    public int? Version { get; set; }

    public string Password { get; set; }

    public long? CacheSize { get; set; }

    // More properties
}

我在想 JSON 可能需要具有相同数量的属性来匹配,或者它可能与数据类型定义有关,但也许这些完全无关。

根据微软文档

当 GetSection 返回匹配的部分时,不会填充 Value。 当该部分存在时,返回一个 Key 和 Path。

如果您想查看该部分的值,您需要调用 GetChildren() 方法: Configuration.GetSection("SqliteSettings").GetChildren();

或者您可以使用: Configuration.GetSection("SqliteSettings").Get<SqliteSettings>() JSON 不需要具有相同数量的属性来匹配。 不匹配的可空属性将被设置为空,不可为空的不匹配属性将被设置为其默认值(例如 int 将被设置为 0)。

  1. 右键单击appsettings.json并转到“属性”。
  2. 选择复制到输出目录 = 始终复制。

只需将您的ConfigureServices方法修改为如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();

    services.Configure<SqliteSettings>(Configuration.GetSection("SqliteSettings"));

    services.AddMvc();
}

它应该工作。

如果所有其他答案都不能解决问题,另一个原因可能是 Options 类的属性是私有的(或者没有可访问的 setter)。

这在控制台应用程序中对我有用:

var connectionString = config["ConnectionStrings:DefaultConnection"]
var serviceProvider = services.BuildServiceProvider();

必须在所有services.Configure调用之后来。

我的问题是 .bind() 方法的对象实例没有初始化。

services.Configure<SqliteSettings>(opts => Configuration.GetSection("SqliteSettings").Bind(opts));

所以在调用 .bind(opts); 之前我初始化了这个值:

SqlliteSettings opts = new SqliteSettings();

绑定本地设置变量:

Configuration.GetSection(AppSettingsSectionName).Bind(opts);

并分别做了容器注册:

services.Configure<AppSettings>(Configuration.GetSection("SqlliteSettings"));

这解决了这个问题,因为 .Bind() 方法将在提供的实例为 null 时返回 null。

如果您的依赖注入失败,并且您在调试后得出结论,该方法是问题所在,则不是!

这足以注册:

services.Configure<SqliteSettings>(Configuration.GetSection("SqliteSettings"));

您必须在IOptions接口中注入您的配置类。 这将解决DI问题。 我在这个问题上浪费了几个小时,希望它可以帮助别人。

对于 Web Api Core 2.1,我需要项目根文件夹(与 Startup.cs 相同的文件夹)中的Program.cs

尝试将 ConfigurationProvider 添加到 ConfigurationBuilder。

应用程序配置来自:

  • appsettings.json 使用文件配置提供程序。
  • appsettings.{Environment}.json 使用文件配置提供程序。

确保您没有意外地将变量嵌套在默认的Logging对象中。 我一直在错误的括号级别中粘贴各种变量(但它在默认的 appsettings.json 中意外正确),导致神秘地缺少键/值。

就我而言,我使用的是 VS Code 和 .net core 3.x webapp。

我遇到了类似的问题,即 GetSection() 或 Configuraton["Section:KeyName"] 返回 null,我检查了 GetSection().Exists() 也返回了 false。

所以我尝试在 ConfigureServices 中添加 configbuilder 这帮助我解决了这个问题,

  public void ConfigureServices(IServiceCollection services)
  {
      //Initialize the builder 
      var builder = new ConfigurationBuilder()
                    .SetBasePath(Environment.CurrentDirectory)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)//To specify environment
                    .AddEnvironmentVariables();//You can add if you need to read environment variables.

      //Build the configuration
      IConfiguration Configuration = builder.Build();

       
      services.Configure<SqliteSettings>(Configuration.GetSection("SqliteSettings"));
      //Similar to below 
      //services.Configure<EntityClass>(Configuration.GetSection("EntityConfigSection"));
      
  }

注意:请确保 .VScode/launch.json 下的 cwd 和 program 值具有正确的值。 代码从 cwd 值中选择当前工作目录,因此我们需要确保其设置正确。

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "X.X.X",
"configurations": [
    {
        "name": ".NET Core Launch (web)",
        "type": "coreclr",
        "request": "launch",
        "preLaunchTask": "build",
        "program": "${workspaceFolder}/<ProjectLocation>/bin/<BuildType>/<Version>/<ProjectDll>",
        "args": [],
        "cwd": "${workspaceFolder}/<ProjectLocation>",
        "stopAtEntry": false,
        "serverReadyAction": {
            "action": "openExternally",
            "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
        },
        "env": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "sourceFileMap": {
            "/Views": "${workspaceFolder}/Views"
        }
    }

]}

确保您的配置对象上有属性访问器,否则它将无法正确绑定。 知道这一点今天可以为我节省 2 个小时。

public class MyConfiguration
{
        public string ConfigurationOption1; // BAD
        public string ConfigurationOption2 { get; set; } // GOOD
}

确保在正确的 appsettings.json 文件中添加代码。 可能有多个 appsettings.json 文件,例如 appsettings.Development.json、appsettings.QA.json,具体取决于项目,因此基于环境,您的代码将被执行。

如果您有appsettings.Development.json文件,请确保appsettings.Development.jsonappsettings.json文件中的“ConnectionStrings:DefaultConnection”设置相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM