Get-Set Hosting Environment
ASP.NET Core Hosting Environment determines the environment in which the application is running. Environments can be of 3 types:
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
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.
Hosting Environment in Controller
We can Get the Hosting Environment in the Controller by injecting IWebHostEnvironment into the constructor of the controller.