Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET core it's possible to configure an action in controller only in development mode?

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?

like image 518
mm98 Avatar asked Jun 07 '19 13:06

mm98


2 Answers

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.

like image 161
Kirk Larkin Avatar answered Nov 01 '22 09:11

Kirk Larkin


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))]

like image 19
Daboul Avatar answered Nov 01 '22 08:11

Daboul