how can dotnet know my environment - staging, development, production?

how can dotnet know my environment - staging, development, production?

I have a dotnet webapi project which can be run in different environments:

  • development environment (localhost)
  • staging environment (Server 1 - IIS deployment)
  • production (Server 2 - IIS deployment)

I also have .env for each of these environments. In my program.cs file, I'm trying to set some features conditionally (e.g only when my software is deployed to production as above), but it doesn't seem to work. Here's my code snippet:

// Program.cs
if (app.Environment.IsProduction())
{
    app.UseHttpsRedirection();
}

When I deploy to staging, I observed that the https redirection still kicks in.

How can I make this work?

Answer

The IWebHostEnvironment.EnvironmentName property (which is used internally by IsProduction(), IsDevelopment(), etc.) is set based on the ASPNETCORE_ENVIRONMENT environment variable. If this variable is not explicitly set, ASP.NET Core assumes the environment is Production by default.

Even though you've deployed to your staging server, unless you've set ASPNETCORE_ENVIRONMENT=Staging on that server, ASP.NET Core will assume it’s Production. Therefore, the condition app.Environment.IsProduction() will return true, and UseHttpsRedirection() will still be applied.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions