ASP.NET Core

Get-Set Hosting Environment

Get-Set Hosting Environment

Get-Set Hosting Environment

ASP.NET Core Hosting Environment determines the environment in which the application is running. Environments can be of 3 types:
Development
Staging
Production


The IWebHostEnvironment has the following 3 methods to determine the hosting environment.
IsDevelopment – returns true if environment is Development.
IsStaging – returns true if environment is Staging.
IsProduction – returns true if environment is Production.


Get Hosting Environment
We can get the Hosting Environment in the Program class

if (app.Environment.IsDevelopment()){
    // do something
}
if (app.Environment.IsStaging()){
    // do something
}
if (app.Environment.IsProduction()){
    // do something
}



Set Hosting Environment
We can set the ASP.NET Core Hosting Environment through the “Properties” page of the application.
In the Solution Explorer and right click on your application name and select Properties.
In the properties page select the Debug option. (in latest visual studio click 'open debug launch profiles UI')
There you will see the current hosting environment is set as “Development” by a variable called ASPNETCORE_ENVIRONMENT. We can change to any as required.

Once you save by pressing CTRL+S in Property page of the app. Visual Studio stores the environment in the launchSettings.json file




Register and User Middlewares only at Production Environment
We can create a condition to register these Middlewares only if the environment is Production.

// in Program.cs file
if (app.Environment.IsProduction())
{
    app.UseMiddleware<ResponseEditingMiddleware>();
}




Hosting Environment in Controller
We can Get the Hosting Environment in the Controller by injecting IWebHostEnvironment into the constructor of the controller.

public class HomeController : Controller
{
    private IWebHostEnvironment hostingEnvironment;  
    public HomeController (IWebHostEnvironment environment)
    {
        hostingEnvironment = environment;
    }

    public IActionResult Index()
    {
        if (env.IsDevelopment()) {
            // ...
        }
 
        if (env.IsStaging()){
            // ...
        }
 
        if (env.IsProduction()){
            // ...
        }
        return View();
    }  
}





Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram