我在appsettings.json文件中有这个
{
"api": {
"users": "/api/users",
"Default": "/api"
}
}
我想将“appsettings.json”反序列化到启动类中以获取value1 =“/ api / users”
结果,sectionData& value1为null,我不知道为什么..
public class Startup
{
public string value1, value2;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// setup DI in service container
services.AddOptions();
services.AddSingleton<IConfiguration>(Configuration);
IConfigurationSection sectionData = Configuration.GetSection("Api").GetSection("Users");
Debug.WriteLine("section Data="+sectionData);
value1 = Configuration.GetSection("api")["users"];
Debug.WriteLine("testvvalue1=" + value1);
}
}
提前感谢您的帮助!
答案 0 :(得分:4)
我猜你的文件没有被阅读。路径有问题 检查你可以放 .AddJsonFile(&#34; appsettings.json&#34;,optional:false,reloadOnChange:true)
并检查它是否会抛出。
其他问题可能是&#34;用户&#34;不是部分而是价值。 我不知道它是如何在内部管理的。你能检查一下吗? Configuration.GetSection(&#34; api&#34;)也为空?