How to Set Aspnetcore_Environment to Be Considered for Publishing an ASP.NET Core Application

How to set ASPNETCORE_ENVIRONMENT variable at runtime

You should configure your hosting environment (Azure/AWS/Container orchestrator/whatever) to set ASPNETCORE_ENVIRONMENT=YourCustomValue environment variable for the app. Each environment should provide different values. For instance, in AWS ECS you would do:

{
"family": "",
"containerDefinitions": [
{
"name": "app",
"image": "app:latest",
...
"environment": [
{
"name": "ASPNETCORE_ENVIRONMENT",
"value": "YourCustomValue"
}
],
...
}
],
...
}

In docker-compose:

version: '3'
services:
app:
image: app:latest
environment:
- ASPNETCORE_ENVIRONMENT: 'YourCustomValue'

If you start it from a shell script:

ASPNETCORE_ENVIRONMENT=YourCustomValue dotnet App.dll

Asp.net core 6 app on Azure uses Development environment by default?

By searching ASPNETCORE_ENVIRONMENT in the solution, I found it to be set to Development in a web.config file. I remember that I tried to run the app locally under IIS but can't remember that I set the variable. I guess it created the file at that time.

So if you are in the same situation, think about the web.config file which could affect the publication to Azure.

Update: I made the test. I created an IIS launch config. VS created the web.config file. Then I manually added ASPNETCORE_ENVIRONMENT in the UI. It added it to the web.config file. In the UI, I then removed the env var. Guess what? It didn't remove it from the file...

Publish to IIS, setting Environment Variable

This answer was originally written for ASP.NET Core RC1. In RC2 ASP.NET Core moved from generic httpPlafrom handler to aspnetCore specific one. Note that step 3 depends on what version of ASP.NET Core you are using.

Turns out environment variables for ASP.NET Core projects can be set without having to set environment variables for user or having to create multiple commands entries.

  1. Go to your application in IIS and choose Configuration Editor.
  2. Select Configuration Editor
  3. Choose system.webServer/aspNetCore (RC2 and RTM) or system.webServer/httpPlatform (RC1) in Section combobox
  4. Choose Applicationhost.config ... in From combobox.
  5. Right click on enviromentVariables element, select 'environmentVariables' element, then Edit Items.
    Sample Image
  6. Set your environment variables.
  7. Close the window and click Apply.
  8. Done

This way you do not have to create special users for your pool or create extra commands entries in project.json.
Also, adding special commands for each environment breaks "build once, deploy many times" as you will have to call dnu publish separately for each environment, instead of publish once and deploying resulting artifact many times.

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



Related Topics



Leave a reply



Submit