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)

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值