• .NET Core配置文件的用法(读取配置文件的值)
  • 发布于 1个月前
  • 61 热度
    0 评论
背景
ASP.NET Core 提供了一个灵活可扩展,基于键值的配置系统. 但是配置系统独立于ASP.NET Core是Microsoft.Extensions 类库的部分. 它可以用于任何类型的应用程序。
1、以键-值对的形式读取配置
 appsettings.json 文件:
{
    "Position": {
        "Title": "堆代码",
        "Address": "https://www.duidaima.com"
    },
    "MyKey": "My appsettings.json Value",
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*"
}
在ConfigureServices方法里面添加如下测试代码:
 var myKeyValue = Configuration["MyKey"];
        var title = Configuration["Position:Title"];
        var address = Configuration["Position:Address"];
        var defaultLogLevel = Configuration["Logging:LogLevel:Default"];
2、多环境配置
使用默认配置,EnvironmentVariablesConfigurationProvider 会在读取 appsettings.json、appsettings.Environment.json 和机密管理器后从环境变量键值对加载配置 。 因此,从环境中读取的键值会替代从 appsettings.json、appsettings.Environment.json 和机密管理器中读取的值 。在 launchSettings.json 中设置的环境变量,在 launchSettings.json 中设置的环境变量将替代在系统环境中设置的变量。

3、读取结构化的配置数据
添加一个类 TestSubSectionConfig 对应于配置文件中的 subsection 节点
public class TestSubSectionConfig
    {
        public string SubOption1 { get; set; }
        public string SubOption2 { get; set; }
    }
在ConfigureServices方法里面添加如下测试代码:
//使用GetSection解析配置文件的节
var subsectionOptions = Configuration.GetSection("subsection").Get<TestSubSectionConfig>();
var suboption2 = subsectionOptions.SubOption2;

Console.WriteLine($"subsection:suboption2: {suboption2}");
如果需要在Controller里面使用,可以通过依赖注入的方式:
在ConfigureServices里面注册配置项。
public void ConfigureServices(IServiceCollection services)
{
    //注册配置到服务容器
    services.Configure<TestSubSectionConfig>(Configuration.GetSection("subsection"));

    //var subsectionOptions = Configuration.GetSection("subsection").Get<TestSubSectionConfig>();
    //services.Configure<TestSubSectionConfig>(options =>
    //{
    //    options.SubOption1 = subsectionOptions["suboption1"];
    //    options.SubOption2 = subsectionOptions["suboption2"];
    // });

}
public class HomeController : Controller
{
    private TestSubSectionConfig _subSectionConfig;
    private ILogger<HomeController> _logger; 

    public HomeController(IOptions<TestSubSectionConfig> option, ILogger<HomeController> logger)
    {
        _subSectionConfig = option.Value;
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation($"SubOption1: {_subSectionConfig.SubOption1}");
        _logger.LogInformation($"SubOption2: {_subSectionConfig.SubOption2}");
        return View();
    }
}

用户评论