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

前端 未结 2 608
礼貌的吻别
礼貌的吻别 2020-12-11 18:04

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

相关标签:
2条回答
  • 2020-12-11 18:32

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

    0 讨论(0)
  • 2020-12-11 18:48

    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.

    0 讨论(0)
提交回复
热议问题