1. 程式人生 > >ASP.NET Core 中的配置

ASP.NET Core 中的配置

ted .com 托管 lee obj 根據 webapi ocs 根目錄

前言

配置在我們開發過程中必不可少,ASP.NET中的配置在 Web.config 中。也可配置在如:JSON、XML、數據庫等(但ASP.NET並沒提供相應的模塊和方法)。

ASP.NET CoreWeb.config已經不存在了(但如果托管到 IIS 的時候可以使用 web.config 配置 IIS),

而是用appsettings.jsonappsettings.(Development、Staging、Production).json配置文件

(可以理解為ASP.NET中的Web.configWeb.Release.config的關系)。

下面我們一起看下ASP.NET Core 中的配置

基礎用法

HomeController.cs

[ApiController]
public class HomeController : ControllerBase
{
    private readonly IConfiguration _configuration;
    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet("/")]
    public dynamic Index()
    {
        return JsonConvert.SerializeObject(new
        {
            ConnectionString = _configuration["ConnectionString"],
            Child1 = _configuration["Parent:Child1"],
            Grandchildren = _configuration["Parent:Child2:Grandchildren"]
        });
    }
}

返回結果:

{
    "ConnectionString": "data source=.;initial catalog=TEST;user id=sa",
    "Child1": "child",
    "Grandchildren": "grandchildren"
}

對應appsettings.json的值:

{
    "ConnectionString": "data source=.;initial catalog=TEST;user id=sa;password=123",
    "Parent": {
        "Child1": "child1",
        "Child2": "child2"
    }
}

需要註意的:

  • 鍵不區分大小寫。 例如,ConnectionString 和 connectionstring 被視為等效鍵。
  • 如果鍵名相同(包含所有加載的配置文件),以最後一個值為準。

    所以appsettings.(Development、Staging、Production).json會覆蓋appsettings.json的配置信息。

    • 多層級用:來分割,但如果是環境變量則存在跨平臺問題 查看具體細節
    • 上面這種寫法是沒緩存的即:appsettings.json修改後,獲取的值會立即改變

綁定到對象 IOptions<TestOptions>

對於_configuration["Parent:Child2:Grandchildren"]的寫法對程序員來說肯定很反感,下面我們看下把配置文件綁定到對象中。

  1. 首先把 JSON 對象轉換成對象

    public class TestOptions
    {
        public string ConnectionString { get; set; }
        public Parent Parent { get; set; }
    }
    public class Parent
    {
        public string Child1 { get; set; }
        public Child2 Child2 { get; set; }
    }
    public class Child2
    {
        public string GrandChildren { get; set; }
    }
  2. Startup.csConfigureServices方法添加代碼:

    services.Configure<TestOptions>(Configuration);
  3. HomeController.cs

    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly IOptions<TestOptions> _options;
    
        public HomeController(IOptions<TestOptions> options)
        {
            _options = options;
        }
    
        [HttpGet("options")]
        public string Options()
        {
            return JsonConvert.SerializeObject(_options);
        }
    }

    返回的結果如下:

    {
    "Value": {
        "ConnectionString": "data source=.;initial catalog=TEST;user id=sa",
            "Parent": {
            "Child1": "child",
                "Child2": {
                "GrandChildren": "grandchildren"
                }
            }
        }
    }

發現

  • 如果我們修改appsettings.json,然後刷新頁面,會發現值並沒用變
  • 我們發現根節點是Value

    根據上面 2 個問題我們去看源代碼:

    首先找到這句:

    services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));

    我們去看OptionsManager方法:

    public class OptionsManager<TOptions> : IOptions<TOptions>, IOptionsSnapshot<TOptions> where TOptions : class, new()
    {
        private readonly IOptionsFactory<TOptions> _factory;
        // 註解: _cache 為 ConcurrentDictionary<string, Lazy<TOptions>>()
        // 不知道註意到上面註入方法沒,用的是 Singleton 單例,所以更新配置文件後沒及時更新
        private readonly OptionsCache<TOptions> _cache = new OptionsCache<TOptions>();
    
        public OptionsManager(IOptionsFactory<TOptions> factory)
        {
            _factory = factory;
        }
    
        /// <summary>
        /// TOptions的默認配置實例
        /// 這裏就是為什麽根節點為Value
        /// </summary>
        public TOptions Value
        {
            get
            {
                return Get(Options.DefaultName);
            }
        }
    
        /// <summary>
        /// 該方法在 IOptionsSnapshot 接口中
        /// </summary>
        public virtual TOptions Get(string name)
        {
            name = name ?? Options.DefaultName;
    
            // Store the options in our instance cache
            return _cache.GetOrAdd(name, () => _factory.Create(name));
        }
    }

綁定到對象 IOptionsSnapshot<TestOptions>

  1. IOptions<TestOptions> 的用法一樣,區別就是依賴註入的生命周期為Scoped,所以沒緩存,直接看代碼:

    services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));

  2. IOptionsSnapshot<TOptions>IOptions<TOptions> 多了個方法TOptions Get(string name);

    Value屬性其實就是調用了該方法,只是nameOptions.DefaultName

  3. IOptionsSnapshot<TOptions> 繼承了 IOptions<TOptions> (這裏有個疑問,上面的OptionsManager<TOptions>繼承了IOptions<TOptions>, IOptionsSnapshot<TOptions>2 個接口,也許是為了清晰吧)。

自定義配置文件(JSON)

有的時候配置信息很多,想在單獨的文件中配置,ASP.NET Core 提供了INIXMLJSON文件系統加載配置的方法。

  1. 首先在 Program.csCreateWebHostBuilder方法中添加如下代碼:

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
     {
         return WebHost.CreateDefaultBuilder(args)
                     .ConfigureAppConfiguration((hostingContext, config) =>
                     {
                         //設置根目錄,我們放在 /Config 文件夾下
                         // 此種寫法不會加載  `appsettings.json`
                         // config.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "Config"));
                         config.SetBasePath(Directory.GetCurrentDirectory());
                         //添加 setting.json 配置文件
                         //optional: 文件是否可選,當為false時 如果文件不存在 程序啟動不起來
                         //reloadOnChange:文件改變後是否重新加載
                         config.AddJsonFile("Config/setting.json", optional: false, reloadOnChange: false);
                     })
                     .UseStartup<Startup>();
     }

    我們看下 reloadOnChange 參數處理了哪些事情:

    if (Source.ReloadOnChange && Source.FileProvider != null)
    {
        ChangeToken.OnChange(
            //監視文件 如果改變就執行 Load(true) 方法
            () => Source.FileProvider.Watch(Source.Path),
            () => {
                Thread.Sleep(Source.ReloadDelay);
                Load(reload: true);
            });
    }
  2. 創建setting.json

    {
            "Rookie": {
                "Name": "DDD",
                "Age": 12,
                "Sex": "男"
            }
    }
  3. 在 Controller 中:

     [Route("api/[controller]")]
     [ApiController]
     public class OptionsController : ControllerBase
     {
         private readonly IConfiguration _configuration;
         public OptionsController(IConfiguration configuration)
         {
             _configuration = configuration;
         }
         [HttpGet]
         public string Index()
         {
             return JsonConvert.SerializeObject(new
             {
                 Name = _configuration["Rookie:Name"],
                 Age = _configuration["Rookie:Age"],
                 Sex = _configuration["Rookie:Sex"]
             });
         }
     }

自定義配置文件(JSON)綁定到對象

通過上面配置發現獲取配置用的是 _configuration["Name"] 方式,下面我們綁定到對象上

  1. 定義配置對象 Setting

  2. Startup.csConfigureServices方法添加代碼:

    services.Configure<Setting>(Configuration.GetSection("Rookie"));

    GetSection方法:獲得指定鍵的配置子部分

  3. 用法和上面一樣

不知道發現個情況沒,我們setting.json的配置文件的信息也是存到_configuration中的,如果文件多了很可能會覆蓋節點,下面我們換一種寫法。

  1. 首先刪除 Program.csCreateWebHostBuilder方法的代碼:

    config.AddJsonFile("Config/setting.json", optional: false, reloadOnChange: true);

  2. 修改配置文件setting.json

    {
       "Name": "DDD",
       "Age": 12,
       "Sex": "男"
    }
  3. 在中Startup.csConfigureServices方法中添加:

    var config = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("Config/setting.json", optional: false, reloadOnChange: true)
                 .Build();
     services.Configure<Setting>(config);

這樣就不會影響 全局 的配置信息了

其他方式

  1. 我們看下下面 2 個方式:

    [Route("[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly TestOptions _bindOptions = new TestOptions();
        private readonly Parent _parent = new Parent();
    
        public HomeController(IConfiguration configuration)
        {
            //全部綁定
            _configuration.Bind(_bindOptions);
            //部分綁定
            _configuration.GetSection("Parent").Bind(_parent);
        }
    
        [HttpGet("options")]
        public string Options()
        {
            return JsonConvert.SerializeObject(new
            {
                BindOptions = _bindOptions,
                Parent = _parent
            });
        }
    }

    個人感覺這種方式有點多余 ( ╯□╰ )

  2. IOptionsMonitorIOptionsFactoryIOptionsMonitorCache 方式:

    我們看如下代碼

    services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));
    services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>)));
    services.TryAdd(ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>)));

    這裏只說下 IOptionsMonitor<>:

     [Route("[controller]")]
     [ApiController]
     public class HomeController : ControllerBase
     {
         private readonly IOptionsMonitor<TestOptions> _optionsMonitor;
    
         public HomeController(IOptionsMonitor<TestOptions> optionsMonitor
         , ILogger<HomeController> logger)
         {
             _optionsMonitor = optionsMonitor;
             _logger = logger;
         }
    
         [HttpGet("options")]
         public string Options()
         {
             //這裏有個變更委托
             _optionsMonitor.OnChange((options, name) =>
             {
                 var info = JsonConvert.SerializeObject(new
                 {
                     Options = options,
                     Name = name
                 });
                 _logger.LogInformation($"配置信息已更改:{info}");
             });
             return JsonConvert.SerializeObject(new
             {
                 OptionsMoitor = _optionsMonitor
             });
         }

    當我們修改配置文件後會看到日誌信息:

    info: WebApiSample.Controllers.HomeController[0]
    配置信息已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
    info: WebApiSample.Controllers.HomeController[0]
    配置信息已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
    info: WebApiSample.Controllers.HomeController[0]
    配置信息已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
    info: WebApiSample.Controllers.HomeController[0]
    配置信息已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}

    不知道為什麽會有這麽多日誌...

    還有一點不管我們修改哪個日誌文件,只要是執行了AddJsonFile的文件,都會觸發該事件

寫在最後

寫的有點亂希望不要見怪,本以為一個配置模塊應該不會復雜,但看了源代碼後發現裏面的東西好多...

本來還想寫下是如何實現的,但感覺太長了就算了。

最後還是希望大家以批判的角度來看,有任何問題可在留言區留言!

ASP.NET Core 中的配置