前提
你已經會使用配置文件,如果還不會使用可以閱讀這篇文章
asp.net core 讀取Appsettings.json 配置文件
簡介
我們需要實現在development環境的配置和production環境的配置略有差異,一般都是因爲 數據庫連接字符串、接口地址、前綴後綴等等一些信息。
文件清單
- appsetting.json //必備,無論是正式還是測試
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"Evn": "正式",
"AllowedHosts": "*"
}
- appsetting.Development.json //測試環境
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Evn": "開發"
}
- appsetting.Production.json //正式環境
{
"Logging": {
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
}
},
"Evn": "生產"
}
配置變量
如下圖
也可以直接在launchSettings.json文件中進行配置(在本機調試時使用),分別對應的iis調試和控制檯調試
在發佈到iis上以後是沒有launchSettings.json文件的,需要在webconfig中進行配置
<?xml version="1.0"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore>
<!--環境配置-->
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
部分代碼
index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Environment Sample"+" "+ (new IndexModel()).Evn;
}
<div class="row">
<h1>Environments Sample</h1>
<p>This sample demonstrates the concepts explained in <a href="https://docs.microsoft.com/aspnet/core/fundamentals/environments">Use multiple environments in ASP.NET Core</a>.</p>
</div>
indexModel.cs
public class IndexModel : PageModel
{
public string Evn = "";
public IndexModel()
{
Evn = Startup.Configuration["Evn"];
}
public void OnGet()
{
}
}
效果
Development
Production(默認不設置也是啓用這個環境)
備註
如果變量在對應的環境配置中找不到會在appsetting.config文件中找