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

前端 未结 2 607
礼貌的吻别
礼貌的吻别 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))]

提交回复
热议问题