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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)