C# 从Microsoft.Extensions.Configuration中读取JSON作为字符串
Microsoft.Extensions.Configuration有自己的API,用于在其读取的配置文件中包含的JSON中导航。(这是ASP.NET用于配置的内容) 对于给定的JSON节点,有没有一种方法可以作为字符串而不是更多的配置对象访问其内容?我的配置文件中有JSON对象,我需要通过JSON反序列化程序运行这些对象(因此我只想从文件中以字符串形式读取此节点) 类似于以下内容的东西:C# 从Microsoft.Extensions.Configuration中读取JSON作为字符串,c#,.net,json,asp.net-core,microsoft.extensions.configuration,C#,.net,Json,Asp.net Core,Microsoft.extensions.configuration,Microsoft.Extensions.Configuration有自己的API,用于在其读取的配置文件中包含的JSON中导航。(这是ASP.NET用于配置的内容) 对于给定的JSON节点,有没有一种方法可以作为字符串而不是更多的配置对象访问其内容?我的配置文件中有JSON对象,我需要通过JSON反序列化程序运行这些对象(因此我只想从文件中以字符串形式读取此节点) 类似于以下内容的东西: var myObjectsSection = configuration.GetSection("
var myObjectsSection = configuration.GetSection("MyObjects");
var innerText = myObjectsSection.InnerText; //Is there any way to do this???
var myObjs = JsonConvert.DeserializeObject<MyObject[]>(innerText);
Asp.net core 3有一种获取类型相关配置值的方法:
T IConfigurationSection.Get()
我试图解析您描述的自定义配置,它正在工作
appsetting.json:
{
"CustomSection": [
{
"SomeProperty": 1,
"SomeOtherProperty": "value1"
}
]
}
启动类:
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection section = this.Configuration.GetSection("CustomSection");
var configs = section.Get<List<CustomSectionClass>>();
}
public class CustomSectionClass
{
public int SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
public void配置服务(IServiceCollection服务)
{
IConfigurationSection=this.Configuration.GetSection(“CustomSection”);
var configs=section.Get();
}
公共类CustomSectionClass
{
公共int SomeProperty{get;set;}
公共字符串SomeOtherProperty{get;set;}
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection section = this.Configuration.GetSection("CustomSection");
var configs = section.Get<List<CustomSectionClass>>();
}
public class CustomSectionClass
{
public int SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
}