In ASP.NET Core, you can check the runtime environment by using the IHostEnvironment interface, which is available in the controller and view.
To check the runtime environment in a controller, you can inject the IHostEnvironment interface into the constructor of the controller and then use the EnvironmentName property to determine the environment. Here is an example:
public class HomeController : Controller
{
private readonly IHostEnvironment _hostEnvironment;
public HomeController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
public IActionResult Index()
{
if (_hostEnvironment.IsDevelopment())
{
// Development environment-specific code
}
else if (_hostEnvironment.IsProduction())
{
// Production environment-specific code
}
return View();
}
}
In View (Razor Pages)
@using Microsoft.AspNetCore.Hosting
@inject IHostEnvironment HostEnvironment
When Core-7 MVC Then
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment hostingEnv
string EnvName = @hostingEnv.EnvironmentName;