ASP.NET Core中读取自定义JSON配置

在ASP.NET中,一般情况下都是通过web.config来设置应用程序配置信息,要使用其它方式(比如JSON文件)来进行配置都需要自行扩展。而ASP.NET Core中就丰富的配置的方式。.

using Microsoft.Extensions.DependencyInjection.ConfigSample.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("MyConfig.json",
                       optional: true,
                       reloadOnChange: true);
});

builder.Services.AddRazorPages();

var app = builder.Build();

JsonConfigurationProvider 从 JSON 文件键值对加载配置。

重载可以指定:

文件是否可选。optional: true,

如果文件更改,是否重载配置。reloadOnChange

通过以下选项将 JSON 配置提供程序配置为加载 MyConfig.json 文件:

optional: true:文件是可选的。

reloadOnChange: true:保存更改后会重载文件。

读取 MyConfig.json 文件之前的默认配置提供程序。MyConfig.json 文件中的设置会替代默认配置提供程序中的设置,包括环境变量配置提供程序和命令行配置提供程序。

private readonly IConfiguration Config;
    public ArrayExample? _array { get; private set; }

    public ArrayModel(IConfiguration config)
    {
        Config = config;
    }

    public ContentResult OnGet()
    {
        if (_array == null)
        {
            throw new ArgumentNullException(nameof(_array));
        }

        _array = Config.GetSection("array").Get<ArrayExample>();
        string s = String.Empty;

        for (int j = 0; j < _array.Entries.Length; j++)
        {
            s += $"Index: {j}  Value:  {_array.Entries[j]} \n";
        }

        return Content(s);
    }
}