In my ASP.NET core web application, I want to have an action that runs only in development mode. In production mode, maybe a 404 error will be good enough. Is it possible to do that?
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
.
One nice way to do it is to create a DevOnlyActionFilter
filter https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2
The filter would look like that:
public class DevOnlyActionFilter : ActionFilterAttribute
{
private IHostingEnvironment HostingEnv { get; }
public DevOnlyActionFilter(IHostingEnvironment hostingEnv)
{
HostingEnv = hostingEnv;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if(!HostingEnv.IsDevelopment())
{
context.Result = new NotFoundResult();
return;
}
base.OnActionExecuting(context);
}
}
And to annotate your controller action with [TypeFilter(typeof(DevOnlyActionFilter))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With