IConfiguration不包含AppSettings

时间:2019-12-26 11:32:44

标签: c# .net-core

在我的API中,我在Startup.cs中具有以下构造函数:

public Startup(IHostingEnvironment env)
{
    IConfigurationBuilder builder = new ConfigurationBuilder()
                                    .SetBasePath(env.ContentRootPath)
                                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                                    .AddEnvironmentVariables();      
    Configuration = builder.Build();
}

调试和/或尝试从appsettings.json中获取值是可行的。

在我的控制器中,我无法获取值,它始终为null。调试时,配置中没有AppSettings部分。

这是我的控制器构造函数:

public ImageController(IImageRepository imageRepository, IMapper mapper, ITagRepository tagRepository, IConfiguration configuration)
{
    _configuration = configuration;

    _imageRepository = imageRepository;
    _tagRepository = tagRepository;
    _mapper = mapper;

    var c = _configuration["AppSettings:ImagesPath"];
}

c始终为空。

这是我的appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "ImagesPath": "/Users/username/temp/skp/"
  }
}

调试时,其中没有AppSettings键 有想法吗?

2 个答案:

答案 0 :(得分:1)

在Startup.cs中的ConfigureServices方法中,您可以检查是否具有:

 services.AddSingleton<IConfiguration>(Configuration);

然后在您的控制器中:

_configuration.GetValue<string>("AppSettings:ImagesPath");

如果失败,请尝试:

var imagesPath = Configuration.GetSection("AppSettings:ImagesPath");

then use .Value to get the actual value

答案 1 :(得分:1)

通常不建议注入IConfiguration

相反,创建一个强类型来绑定所需的设置

public class AppSettings {
    public string ImagesPath { get; set; }
}

并在启动时进行配置

public void ConfigureServices(IServiceCollection services) {

    //...omitted for brevity

    AppSettings settings = Configuration.GetSection(nameof(AppSettings)).Get<AppSettings>();
    services.AddSingleton(settings);

    //...
}

现在可以将控制器重构为预期的强类型设置

public ImageController(IImageRepository imageRepository, IMapper mapper, 
    ITagRepository tagRepository, AppSettings settings) {

    _imageRepository = imageRepository;
    _tagRepository = tagRepository;
    _mapper = mapper;

    var imagesPath = settings.ImagesPath; //<--
}