Suganya
Suganya

Reputation: 171

How to check whether the code is running in development or Production mode in Program.cs file in ASP.NET CORE 2.1?

I have a web application which is developed in ASP.NET CORE 2.1. I want the code to behave differently in Development and Production mode. I tried #if Debug else code but that will not suit my requirement.

Can anyone suggest me how to find the current mode in C# in Program.cs file?

Upvotes: 10

Views: 15484

Answers (1)

Alex Wiese
Alex Wiese

Reputation: 8370

The IWebHostEnvironment interface provides the method IsDevelopment(). Simply inject that into whatever class you're trying to use it from.

public class MyClass
{    
    public MyClass(IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            // Run development specific code
        }
    }
}

If you really need to access it from outside of the DI container/scope then you can theoretically read the value of the ASPNETCORE_ENVIRONMENT environment variable. Take note that this is an implementation detail, and by accessing it that way you're bypassing the framework.

var isDevelopment = string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "development", StringComparison.InvariantCultureIgnoreCase);

Upvotes: 30

Related Questions