ASP.Net Core appsetting.json多环境配置 development 和Production环境

前提

你已经会使用配置文件,如果还不会使用可以阅读这篇文章
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文件中找

源码

源码地址(github)

原文地址:https://www.cnblogs.com/xiaoch/p/13417926.html