.net core 中 appsettings.json 如何读取与进行划分开发、生产不同配置

读取 appsettings.json 相关配置

1、appsettings.json如下

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
    "AllowedHosts": "*"
  },
  "ConfigSetting": {
    "Ctu": 1,
    "Btu": "Btu",
    "Atu": "Atu"
  }
}

2、建立实体ConfigSetting

    public class ConfigSetting
    {
        public int Ctu { get; set; }
        public string Btu { get; set; }
        public string Atu { get; set; }
    }

3、Startup配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.Configure<ConfigSetting>(Configuration.GetSection("ConfigSetting"));
}

4、Controller配置

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IOptions<ConfigSetting> _ConfigSettingt;
        public ValuesController(IOptions<ConfigSetting> ConfigSetting)
        {
            _ConfigSettingt = ConfigSetting;
        }
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return _ConfigSettingt.Value.Atu;
        }
    }

 

appsettings.json 进行划分开发、生产不同配置

1、.net core 默认会有 appsettings.Development.json 文件,这是根据ASPNETCORE_ENVIRONMENT来读取的。

2、新建架构appsettings.Production.json用于生成环境

3、开发调试时通过此处进行配置。

4、正式环境发布

IIS版本 - - - 通过生成的 web.config 进行配置 ASPNETCORE_ENVIRONMENT 环境变量

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\TTTTTTTTT.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" /><!--Development-->
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Credentials" value="true" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

后续更新。。。。

 

posted @ 2019-09-27 15:27  風飄絮℃  阅读(3524)  评论(2编辑  收藏  举报