Talking appsettings.json in Asp.Net Core

來源:互聯網
上載者:User

標籤:分享圖片   asp   netcore   alt   develop   根據   name   png   product   

在ASP.NET Core中,預設提供了三個運行時環境變數,通過查看Hosting原始碼我們可以看到,分別是Development、Staging、Production

public static class EnvironmentName{    public static readonly string Development = "Development";    public static readonly string Staging = "Staging";    public static readonly string Production = "Production";}

當啟動一個ASP.NET Core應用程式時,會確定當前應該運行哪個環境中。預設情況下,如果沒有指定環境變數,會自動預設為Production

public class HostingEnvironment : IHostingEnvironment, Extensions.Hosting.IHostingEnvironment{    public string EnvironmentName { get; set; } = Hosting.EnvironmentName.Production;    public string ApplicationName { get; set; }    public string WebRootPath { get; set; }    public IFileProvider WebRootFileProvider { get; set; }    public string ContentRootPath { get; set; }    public IFileProvider ContentRootFileProvider { get; set; }}

在新建立的ASP.NET Core Web Application中我們會看到了兩個設定檔分別是appsettings.json和appsettings.Development.json。事實上我們還可以添加兩個檔案分別是appsettings.Staging.json和appsettings.Production.json,分別是預生產環境和生產環境。根據環境變數的名稱會載入具體的設定檔。

config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

 可以用面相對象的方式理解這幾個檔案,appsettings.json作為父類,其他幾個檔案作為子類,當兩個設定檔中定義了同一個節點,會以子類的配置為準,相當於orverwrite。如果對應的設定檔中沒有找到節點,會從父類中去尋找。

如果我們的應用程式運行在Docker容器中,Docker也允許在Dockerfile中使用ENV指定環境變數

FROM microsoft/aspnetcore:2.0.5WORKDIR /appEXPOSE 80COPY . .ENV ASPNETCORE_ENVIRONMENT ProductionENTRYPOINT ["dotnet", "WebApplication1.dll"]

還有一種方式是在運行容器的時候使用-e參數

docker run -e ASPNETCORE_ENVIRONMENT=Development -p 5000:5000 <image>:<tag>

 

Talking appsettings.json in Asp.Net Core

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.