ChatGPT解决这个技术问题 Extra ChatGPT

How to set aspnetcore_environment in publish file?

I have ASP.NET Core application (Web Api). The documentation has explained working with multiple environments, however it failed to explain how to set aspnetcore_environment when publishing the web site.

So lets say if i have 3 environments Development, Staging and Production

In classic ASP.NET Web Application i used to create 3 build configurations. Development, Staging and Production ( Like shown in picture below). and then 3 .pubxml files, one for each configuration. Do i need to use the same approach for ASP.NET Core application as well? How do i set aspnetcore_environment in .pubxml file? If the approach specified in Question 1 is obsolete, then what's the alternate approach? ( I use Jenkins for CI)

https://i.stack.imgur.com/8K8Zs.png

Update 1

I understand that I have to set ASPNETCORE_ENVIRONMENT however I am not able to understand where do we set this? During development I can set this in profile in launchSettings.json, however question was how do we set this when publishing to staging or production? do we set environment variable on the target server itself?

https://i.stack.imgur.com/55kOO.png

Update 2
I found article here that explains different ways of setting environment variable. This partially answered my question. However when I publish the application, the publish process does not honor the environment variable while publishing appsettings.{env.EnvironmentName}.json
I have created separate post for that question

Possible duplicate of Pass hosting environment for self-hosting. The question has been answered there already. Just use commandline/powershell/bash/azureportal to set an environment variable

S
Sheldon Nunes

You could pass in the desired ASPNETCORE_ENVIRONMENT into the dotnet publish command as an argument using:

/p:EnvironmentName=Staging

e.g. dotnet publish /p:Configuration=Release /p:EnvironmentName=Staging

This will generate out the web.config with the correct environment specified for your project:

    <environmentVariables>
      <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
    </environmentVariables>

it is possible to set this in publish profile somehow ?
Yes @Muflix. Adding <EnvironmentName>Staging</EnvironmentName> in my .pubxml file has the same effect on the web.config file.
thanks Microsoft waste me few hour and undocument this hidden feature....
A
Abhinav Galodha

I had the same requirement, and I came up with the following solutions. This works well with automated deployments and require fewer configuration changes.

1. Modifying the project file (.CsProj) file

MSBuild supports the EnvironmentName Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.

Simply open the project file (*.csProj) and add the following XML.

    <!-- Custom Property Group added to add the Environment name during publish
  The EnvironmentName property is used during the publish for the Environment variable in web.config
  -->
  <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
    <EnvironmentName>Development</EnvironmentName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
    <EnvironmentName>'$(Configuration)'</EnvironmentName>
  </PropertyGroup>

Above code would add the environment name as Development for empty or Debug configuration. For any other Configuration the Environment name would be picked from the configuration which was selected. This will add the ASPNETCORE_ENVIRONMENT environment with the desired configuration. You can modify the logic for environment name as desired by updating the CsProj file. More details here

2. Adding the EnvironmentName Property in the publish profiles.

We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

https://i.stack.imgur.com/FdH8e.png

As shown in above image, environment can be added for each configuration and the name of the EnvironmentName property can be changed in each *.pubxml file.

3. Command line options using dotnet publish

Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.

dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development


#2 Here is the real answer.
The #2 is the answer for me too, but needed to scroll and read a lot, then finally find it the Microsoft Docs docs.microsoft.com/en-us/aspnet/core/host-and-deploy/…
The #2 unfortunately does not work for me :/ I have to edit web.config directly, don't know what i do wrong.
#2 is working great because it modifies the web.config and changes the ASPNETCORE_ENVIRONMENT value during the Publish process.
The problem I see here is that Environment is not the same as Configuration. I would like to have only Debug and Release configurations for any of my environments: Development, Staging, Production.
s
spottedmahn

When hosting the application under IIS you can set the environment variable in web.config.

https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module

To generate it on publish add a web.config to the root of your project, "dotnet publish" will use this file as the basis for the one that is generated for in the publish folder. Then you can change the value in your deployment system.

<?xml version="1.0" encoding="utf-8" ?>
<!-- Used to overwrite settings web.config generated by "dotnet publish", Only used when hosting under IIS -->
<configuration>
 <system.webServer>
   <aspNetCore stdoutLogEnabled="true">
     <environmentVariables>
       <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
     </environmentVariables>
   </aspNetCore>
 </system.webServer>  
</configuration>

but then you have to create multiple web.config, one for each supported environment like development, uat, prod etc. I found answer in this SO post stackoverflow.com/questions/40748518/… You can set environment variable in IIS directly at application level
Depends a little on use case, if it's it's a corporate environment where you don't have control over the hosting servers doing it by web.config might be the best option as getting someone to update the IIS config or user environment might be a long process. If you do have control over the server setting the environment variable might be the better option.
How do you change the value dynamically during the deployment? Will publish takes care of it?
@LP13 That's the key, isn't it. I don't have a problem with Development and Staging -- development is local, and Staging is on a separate IIS server -- but this answer won't help me to get Production working on a third server.
r
regnauld

I think you can't do it in the publish profile. You have to set environment variable, e.g. ASPNETCORE_ENVIRONMENT = Staging. I had to do a similar thing with a aspnet core web app on Azure. I wanted to have dev, staging and production. The way I did it was exactly with env variable.


V
VMAtm

To setup two or more profiles, you need to create additional profile, as mentioned in a linked article, and your launchSettings.json will contain an array:

"profiles": {
  "IIS Express": {
    "commandName": "IISExpress",
    "launchBrowser": true,
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  },
  "IIS Express (Staging)": {
    "commandName": "IISExpress",
    "launchBrowser": true,
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Staging"
    }
  }
}

To be able to read the environment variable, you need to specify it during startup and call additional method AddEnvironmentVariables to variables take action:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            // general properties
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            // specify the environment-based properties
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            // do not forget to add environment variables to your config!
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }
}

Surely that's not useful in publishing? That's for launching it locally.
It's perfectly useful with continuous integration
R
Rahul Uttarkar

Simple way to set it in visual studio IDE.

Project > Properties> Debug > Environment variables

https://i.stack.imgur.com/2R0oX.png

Please do not use environment variables of machine level instead scope to the application , there is a possibility of other application doing same, changing may affect other application.


Need to modify the config file