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
One nice way to do it is to create a DevOnlyActionFilter filter https://docs.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))]
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.