在我的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 works获取一个值。
在我的控制器中,我不能得到一个值,它总是空的。调试时,配置中没有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-keys,你知道吗?
发布于 2019-12-26 19:43:47
在你的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发布于 2019-12-26 20:09:24
通常不建议注入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; //<--
}https://stackoverflow.com/questions/59487839
复制相似问题