Publish to IIS, set an environment variable

Reading These Two Questions / Answers I was able to run the Asp.net 5 application on the IIS 8.5 server.

Asp.net vNext early beta publishes in IIS on a Windows server

How to configure MVC6 application to work with IIS?

The problem is that the web application still uses env.EnvironmentName with a value of Development even when working in IIS.

In addition, I want to run two versions of the same Web (Staging, Production) on the same server, so I need a method to set a variable for each website separately.

How to do it?

+115
iis asp.net-core visual-studio-2015 asp.net-core-mvc
Jun 25 '15 at 11:31
source share
14 answers

This answer was originally written for ASP.NET Core RC1. In RC2, ASP.NET Core moved from a generic httpPlafrom handler to an aspnetCore-specific one. Please note that step 3 depends on which version of ASP.NET Core you are using.

It turns out that environment variables for ASP.NET Core projects can be set without having to set environment variables for the user or create multiple command entries.

  1. Go to your application in IIS and select Configuration Editor .
  2. Select Configuration Editor
  3. Select system.webServer/aspNetCore (RC2 and RTM) or system.webServer/httpPlatform (RC1) in the Section combo system.webServer/httpPlatform
  4. Select Applicationhost.config ... in the From drop-down list.
  5. Right-click the enviromentVariables element, select the 'environmentVariables' element , then Edit Items . enter image description here
  6. Set environment variables.
  7. Close the window and click "Apply."
  8. Done

This way you do not need to create special users for your pool or create additional command entries in project.json . In addition, adding special commands for each environment violates the โ€œbuild once, deploy many timesโ€, since you have to call dnu publish separately for each environment, instead of publishing once and deploying the resulting artifact repeatedly.

Updated for RC2 and RTM, thanks to Mark G and Tredder.

+246
Apr 25 '16 at 9:23
source share

Update the web.config file with the <environmentVariables> section in the <aspNetCore> section

 <configuration> <system.webServer> <aspNetCore .....> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> </environmentVariables> </aspNetCore> </system.webServer> </configuration> 

Or, in order not to lose this parameter when rewriting web.config, make the same changes to applicationHost.config, indicating the location of the site, as @NickAb suggests.

 <location path="staging.site.com"> <system.webServer> <aspNetCore> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> <location path="production.site.com"> <system.webServer> <aspNetCore> <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" /> </environmentVariables> </aspNetCore> </system.webServer> </location> 
+30
May 26 '16 at 8:33 a.m.
source share

Edit: in RC2 and RTM, this tip is deprecated. The best way to do this in the release is to edit the following sections of web.config in IIS for each environment:

system.webServer/aspNetCore :

Edit the environmentVariable entry and add the environment variable parameter:

ASPNETCORE_ENVIRONMENT : < Your environment name >




As an alternative to the drpdrp approach, you can do the following:

  • In your project.json, add commands that pass the ASPNET_ENV variable directly to Kestrel:

     "commands": { "Development": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development", "Staging": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Staging", "Production": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Production" } 
  • When publishing, use the --iis-command option to specify the environment:

     dnu publish --configuration Debug --iis-command Staging --out "outputdir" --runtime dnx-clr-win-x86-1.0.0-rc1-update1 

I found this approach less intrusive than creating additional IIS users.

+21
Feb 29 '16 at 15:05
source share

After an intensive Google search, I found a working solution that consists of two steps.

The first step is to set the system-wide ASPNET_ENV environment variable to production and restart Windows Server . After that, all web applications get the value "Production" as the EnvironmentName.

The second step (to enable the 'Staging' value for the staging network) was pretty hard to get to work correctly, but here it is:

  1. Create a new Windows user, such as StagingPool on the server.
  2. For this user, create a new ASPNETCORE_ENVIRONMENT user variable with the value 'Staging' (you can do this by logging in as this user or through regedit)
  3. Returning as an administrator in IIS Manager, find the application pool where the intermediate network is running, and in the "Advanced Settings" section, set the StagingPool user identity .
  4. Also set the Load User Profile to true to load environment variables. <- very important!
  5. Make sure StagingPool has permissions to the web folder, and stop and start the application pool.

Now the EnvironmentName "Staging" should be set in the Staging web.

Update: Windows 7+ has a command that can set environment variables from the CMD prompt also for the specified user. These findings help plus samples:

 >setx /? 
+16
Jun 25 '15 at 11:42
source share

I have web applications (PRODUCTION, START, TEST) hosted on the IIS web server. Thus, it was not possible to rely on the ASPNETCORE_ENVIRONMENT life-support environment variable, since setting it to a specific value (for example, STAGING) affects other applications.

In the process, I defined a custom file (envsettings.json) in my visualstudio solution:

enter image description here

with the following content:

 { // Possible string values reported below. When empty it use ENV variable value or Visual Studio setting. // - Production // - Staging // - Test // - Development "ASPNETCORE_ENVIRONMENT": "" } 

Then, based on my type of application (Production, Staging or Test), I install this file as follows: suppose I deploy the TEST application, I will have:

 "ASPNETCORE_ENVIRONMENT": "Test" 

After that, just extract this value in the Program.cs file, and then set up the webHostBuilder environment:

  public class Program { public static void Main(string[] args) { var currentDirectoryPath = Directory.GetCurrentDirectory(); var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json"); var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath)); var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString(); var webHostBuilder = new WebHostBuilder() .UseKestrel() .CaptureStartupErrors(true) .UseSetting("detailedErrors", "true") .UseContentRoot(currentDirectoryPath) .UseIISIntegration() .UseStartup<Startup>(); // If none is set it use Operative System hosting enviroment if (!string.IsNullOrWhiteSpace(enviromentValue)) { webHostBuilder.UseEnvironment(enviromentValue); } var host = webHostBuilder.Build(); host.Run(); } } 

Remember to include envsettings.json in publishOptions (project.json):

  "publishOptions": { "include": [ "wwwroot", "Views", "Areas/**/Views", "envsettings.json", "appsettings.json", "appsettings*.json", "web.config" ] }, 

This solution allows me to have an ASP.NET CORE application hosted on the same IIS, regardless of the value of the envoroment variable.

+14
Feb 09 '17 at 17:28
source share

To extend the answer to @tredder, you can change the environment variables using appcmd

Staging

%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST

Products

%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST

+7
Jun 24 '16 at 9:02
source share

Alternatively, you can pass the desired ASPNETCORE_ENVIRONMENT to the dotnet publish command as an argument using:

 /p:EnvironmentName=Staging 

eg:

 dotnet publish /p:Configuration=Release /p:EnvironmentName=Staging 

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

 <environmentVariables> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> 
+7
Oct 30 '18 at 3:18
source share

What you need to know in one place:

  • For environment variables to override any configuration parameters, they must be prefixed with ASPNETCORE_ .
  • If you want to map child nodes in your JSON configuration, use : as a separator. If the platform does not allow colons in environment variable keys, use __ instead.
  • You want your settings to end up in ApplicationHost.config . Using the IIS configuration editor will cause your input to be written to the Web.config application - and will be overwritten the next time you deploy!
  • To modify ApplicationHost.config you want to use appcmd.exe to make sure your changes are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore/+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']"/commit:site

  • Characters that are not URL safe can be escaped as Unicode, for example %u007b for the left curly bracket.

  • To get a list of current settings (in combination with the values โ€‹โ€‹from Web.config): %systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
  • If you run the command to install the configuration key several times for the same key, it will be added several times! To delete an existing value, use something like %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore / -"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']"/commit:site .
+6
Mar 19 '18 at 18:59
source share

The @tredder solution with editing applicationHost.config is the one that works if you have several different applications located in virtual directories in IIS.

My business:

  • I have an API and APP project in the same domain, which is located in different virtual directories
  • The root page XXX does not seem to propagate the ASPNETCORE_ENVIRONMENT variable to its children in virtual directories and ...
  • ... I canโ€™t set the variables inside the virtual directory as described in @NickAb (an error was received. Request is not supported. (Exception from HRESULT: 0x80070032) while saving changes to the editor configuration):
  • Going to applicationHost.config and manually creating these nodes:

    <location path="XXX/app"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> <location path="XXX/api"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location>

and restarting IIS completed the task.

+5
Sep 23 '16 at
source share

Besides the options mentioned above, there are several other solutions that work well with automated deployments or require fewer configuration changes.

1. Modifying a project file (.CsProj)

MSBuild supports the EnvironmentName property, which can help set the correct environment variable according to the environment you want to deploy. The environment name will be added to the web.config file at the publishing stage.

Just 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>Production</EnvironmentName> </PropertyGroup> 

The above code adds the environment name as Development for the debug configuration, or if no configuration is specified. For any other configuration, the environment name will be Production in the generated web.config file. More here

2. Adding the EnvironmentName property to publication profiles.

We can also add the <EnvironmentName> property to the publication profile. Open the publication profile file, which is located in Properties/PublishProfiles/{profilename.pubxml} . This will set the environment name in web.config when publishing the project. More here

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

3. Command line options using dotnet publish

In addition, we can pass the EnvironmentName property as a command line parameter to the dotnet publish command. The following command will include the environment variable as Development in the web.config file.

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

+5
Jan 30 '19 at 2:14
source share

As with the other answers, I wanted the ASP.NET Core 2.1 environment settings to be preserved during deployment, but also applied only to a specific site.

According to Microsoft documentation, in IIS 10 you can set the environment variable in the application pool using the following PowerShell command:

 $appPoolName = "AppPool" $envName = "Development" cd "$env:SystemRoot\system32\inetsrv" .\appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='$appPoolName'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='$envName']" /commit:apphost 

Unfortunately, I still have to use IIS 8.5 and thought I was out of luck. However, you can still run a simple PowerShell script to set the environment variable for the site to ASPNETCORE_ENVIRONMENT:

 Import-Module -Name WebAdministration $siteName = "Site" $envName = "Development" Set-WebConfigurationProperty -PSPath IIS:\ -Location $siteName -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value @{ Name = 'ASPNETCORE_ENVIRONMENT'; Value = $envName } 
+3
Oct 25 '18 at 17:44
source share

To get detailed error information, I had to add the ASPNETCORE_ENVIRONMENT environment ASPNETCORE_ENVIRONMENT for the corresponding application pool system.applicationHost/applicationPools .

Note. In my case, the web application was an ASP.NET Core 2 web application hosted on IIS 10 . This can be done using the Configuration Editor in IIS Manager (see " Editing Collections Using the Configuration Editor " to find out where to find this editor in IIS Manager ).

0
Apr 25 '18 at 19:13
source share

I created a repository for publishing IIS with environment configuration in Web.config.

https://github.com/expressiveco/AspnetCoreWebConfigForEnvironment

  • Tune
    • Get sections from .csproj and .user.csproj files into your project files.
    • Get the files MyAspNetEnvironment.props, web.development.config and web.production.config.
  • configuration
    • Change the value of the ASPNETCORE_ENVIRONMENT property in user.csproj accordingly.
0
May 15 '18 at 9:39
source share

Github has a well-documented tool for xdt conversions . It is also command independent, and dotnet publish and dotnet msbuild work fine.

You must create various web.config files such as web.debug.cofig, web.release.config, etc. Based on this, you can easily set your own environment variable.

0
Jul 24 '18 at 7:38
source share



All Articles