04. Asp.Net Core 3.x 筆記 配置文件

配置文件優先級

1.appsettings.json
2.appsettings.{xxxx}.json,比如: appsettings.Development.json
3.環境變量
4.命令行

越靠後,優先級越高,將覆蓋前者

添加自定義配置

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

    "Three": {
    "BoldDepartmentEmployeeCountThreshold": 30
  }

}

獲取及其使用配置項:

  • Startup.cs
    public class Startup
    {
        private readonly IConfiguration configuration;
        public Startup(IConfiguration configuatuion)
        {
            configuration = configuatuion;
            var three = configuration["Three:BoldDepartmentEmployeeCountThreshold"];
        }

自定義配置對象及其獲取

  • 自定義配置對象 ThreeOptions
    public class ThreeOptions
    {
        public int BoldDepartmentEmployeeCountThreshold { get; set; }
        public int MyProperty { get; set; }
    }
  • 註冊配置對象
    public class Startup
    {
        private readonly IConfiguration configuration;
        public Startup(IConfiguration configuatuion)
        {
            configuration = configuatuion;
            //var three = configuration["Three:BoldDepartmentEmployeeCountThreshold"];
        }

        //註冊服務
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.Configure<ThreeOptions>(configuration.GetSection("Three"));
        }
  • xxxControler中使用:
    public class DepartmentController : Controller
    {
        private readonly IOptions<ThreeOptions> threeOptions;

        public DepartmentController(IDepartmentService departmentService, IOptions<ThreeOptions> threeOption)
        {
            this.departmentService = departmentService;
        }
  • 在Views使用xxx.cshtml中使用:
@model Three.Models.Department
@inject Microsoft.Extensions.Options.IOptions<Three.ThreeOptions> options
...
        @if (Model.EmployeeCount > options.Value.BoldDepartmentEmployeeCountThreshold)
        {
...
        }
...

自定義配置文件

  • myconfig.json
{
  "Three": {
    "BoldDepartmentEmployeeCountThreshold": 1000
  }
}

Program.cs


        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, configBuilder) => 
                {
                    //configBuilder.Sources.Clear();
                    configBuilder.AddJsonFile("myconfig.json");
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

myconfig.json 會覆蓋 appsettings.json 相同的配置項

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章