This can be achieved by injecting IHostEnvironment
into your controller and using its IsDevelopment()
method inside of the action itself. Here’s a complete example that returns a 404 when running in anything other than the Development environment:
public class SomeController : Controller
{
private readonly IHostEnvironment hostEnvironment;
public SomeController(IHostEnvironment hostEnvironment)
{
this.hostEnvironment = hostEnvironment;
}
public IActionResult SomeAction()
{
if (!hostEnvironment.IsDevelopment())
return NotFound();
// Otherwise, return something else for Development.
}
}
If you want to apply this more globally or perhaps you just want to separate out the concerns, Daboul explains how to do so with an action filter in this answer.
For ASP.NET Core < 3.0, use IHostingEnvironment
in place of IHostEnvironment
.