How to publish environment specific appsettings in .Net core app?

后端 未结 12 2426
刺人心
刺人心 2020-12-04 15:33

I have 3 environment specific appsettings files in my .Net core application

in project.json I have setup publishOptions

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 15:53

    I recently had to find a solution for this as well and I accomplished it by adding some settings to the .csproj file and a minor change to Program.cs.

    
        
        
            true
            full
            DEBUG;TRACE
            Development
        
        
            pdbonly
            true
            Production
        
        
            pdbonly
            true
            Staging
        
        
            
            
        
        
            
            
            
        
    
        
            
        
    
    

    To explain it a little, I added an element for each configuration so it can be used during the build process. I'm using appsettings.{EnvironmentName}.json (i.e. appsettings.Staging.json) just as an "overrides" file so I just have it rename the necessary JSON file during the build process. When you run dotnet publish -c Stage, for example, it will publish the appsettings.Staging.json file into the publish folder and rename it to appsettings.overrides.json. In your Program.cs, you will just need to include the appsettings.overrides.json file as well:

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

    I hope it helps!

    Side note: I include appsettings.*.json and set it to CopyToOutputDirectory="Never" just so they still show up in Visual Studio when developing. Otherwise, if you only want the current environment's appsettings file to show in VS, just remove that line from the csproj file.

提交回复
热议问题