This can be achieved by injecting IHostingEnvironment
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 IHostingEnvironment hostingEnvironment;
public SomeController(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
public IActionResult SomeAction()
{
if (!hostingEnvironment.IsDevelopment())
return NotFound();
// Otherwise, return something else for Development.
}
}
For ASP.NET Core 3.0+, use IWebHostEnvironment
or IHostEnvironment
in place of IHostingEnvironment
.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…