![](/img/trans.png)
[英]Newly generated ASP.NET Core 3.1 app won't run due to Startup.Configure NullReferenceException
[英]ASP.NET Core 3.1 - Configure custom JSON in Startup
尝试将自定义 JSON 文件和 map 配置到相关数据 Model。 能够使其在 class 级别工作,但试图在启动时实现相同的目标。 我非常感谢您的帮助。 谢谢。
// This works.
Class A
public static string GetData(string name)
{
var jsonFile = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, $"customSettings.json"););
var res = JsonConvert.DeserializeObject<Formats>(jsonFile);
}
尝试实现以下目标,即 map CustomSettings.json到Startup.cs中的Formats
并将其作为范围 object 传递。
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// this field is from appsettings.json.
services.Configure<AppDM>(Configuration.GetSection("SomConfigFrom_appsettings"));
// custom mapping : customSettings.json
services.Configure<Formats>(Configuration.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
....
}
customSettings.json
{
"Formats": [
{
"Name": "FormatA"
}
]
class AppDM
{
string a { get; set; }
}
class Formats
{
string Name { get; set; }
}
步骤1
要在配置中添加额外的 JSON 文件,请添加以下行:
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("customSettings.json", optional: true, reloadOnChange: true);
})
在Program.cs中如下:
using System.IO;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("customSettings.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
第2步
从附加的 JSON 文件中, Formats
是一个对象数组。 它应该读作List<FormatConfig>
类型。
在Startup.cs中,
public void ConfigureServices(IServiceCollection services)
{
services.Configure<List<FormatConfig>>(Configuration.GetSection("Formats"));
...
}
public class FormatConfig
{
public string Name { get; set; }
}
第 3 步
在YourController.cs中,通过构造函数注入获取配置依赖IOptions<List<FormatConfig>>
,如下所示:
public class YourController : ControllerBase
{
private readonly IOptions<List<FormatConfig>> _formatConfigOption;
public YourController(/* Other dependencies */
IOptions<List<FormatConfig>> formatConfigOption)
{
...
_formatConfigOption = formatConfigOption;
}
[HttpGet("GetFormatConfig")]
public List<FormatConfig> GetFormatConfig()
{
return _formatConfigOption.Value;
}
}
演示
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.