ASP.NET Core appsettings.json 文件

ASP.NET Core appsettings.json 文件

在本節中,我們將討論 ASP.NET Core 項目中appsettings.json文件的重要性。

在以前的 ASP.NET 版本中,我們將應用程序配置設置(例如數據庫連接字符串)存儲在web.config文件中。 在 Asp.Net Core 中, 應用程序配置設置可以來自以下不同的配置源。

  • 文件(appsettings.json, appsettings..json) Environment環境不同,託管在對應環境。
  • User secrets (用戶機密)
  • Environment variables (環境變量)
  • Command-line arguments (命令行參數)

appsettings.json文件: 我們的項目是通過 Asp.net Core 預製的"空"模板創建的,所以我們的項目中已經有一個 appsettings.json 的文件了。 我們可以對文件進行如下修改,補充一個MyKey的鍵值對:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyKey": " appsettings.json中Mykey的值"
}

訪問配置信息

若要訪問 "Startup " 類中的配置信息, 請注入框架提供的 IConfiguration服務。Startup類位於 startup. cs 文件中。

public class Startup
{
    private IConfiguration _configuration;

    //注意,我們在這裏使用了依賴注入
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(_configuration["MyKey"]);
        });
    }
}

依賴注入

在以前版本的 ASP.NET 中,依賴注入是可選的,要配置它,我們必須使用像 Ninject,autofac、castle windsor 等第三方框架。

在 asp. net Core 中, 依賴注入是不可或缺的一部分。依賴注入能使我們能夠創建低耦合、可擴展且易於測試的系統。

我們將在即將推出的視頻中詳細討論依賴注入,盡情期待。

ASP.NET Core IConfiguration 服務

  • IConfiguration 服務是爲了從 asp.net Core 中的所有各種配置源讀取配置信息而設計的。
  • 如果在多個配置源中具有相同密鑰名稱的配置設置,簡單來說就是重名了,則後面的配置源將覆蓋先前的配置源  。
  • 靜態類WebHostCreateDefaultBuilder()方法在應用程序啓動時會自動去調用,按特定順序讀取配置源。
  • 要查看配置源的讀取順序,請查看以下鏈接上的ConfigureAppConfiguration()方法 https://github.com/aspnet/MetaPackages/blob/release/2.2/src/Microsoft.AspNetCore/WebHost.cs

檢查文件後,您將看到,以下是讀取各種配置源的默認順序

  1. appsettings.json,
  2. appsettings..json
  3. 用戶機密
  4. 環境變量 5.命令行參數

如果您想要改變他們的調用順序,甚至往裏面添加屬於自己的自定義配置信息,我們將在後面的課程中討論如何自定義配置源。

小結

所以翻源代碼也沒有那麼可怕嘛

///<summary>
        ///Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults using typed Startup.
        ///</summary>
        ///<remarks>
        ///  The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///    use Kestrel as the web server and configure it using the application's configuration providers,
        ///    set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///    load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///    load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///    load <see cref="IConfiguration"/> from environment variables,
        ///    load <see cref="IConfiguration"/> from supplied command line args,
        ///    configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///    enable IIS integration.
        ///</remarks>
        ///<typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam>
        ///<param name="args">The command line args.</param>
        ///<returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder<TStartup>(string[] args) where TStartup : class =>
            CreateDefaultBuilder(args).UseStartup<TStartup>();

 

歡迎添加個人微信號:Like若所思。

歡迎關注我的公衆號,不僅爲你推薦最新的博文,還有更多驚喜和資源在等着你!一起學習共同進步!


 

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