Search code examples
asp.netattributesactionfilterattribute

Creating an action filter attribute that bypasses the actual execution of the action and returns a value for it


Can I create an ActionFilterAttribute that bypasses the actual execution of the action and returns a value for it?


Solution

  • You can, like this:

    1) Redirects to some action and then return some value:

    public class MyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            /*If something happens*/
            if (/*Condition*/)
            {
                /*You can use Redirect or RedirectToRoute*/
                filterContext.HttpContext.Response.Redirect("Redirecto to somewhere");
            }
    
            base.OnActionExecuting(filterContext);
        }
     }
    

    2) Write some value direcly into the request and Ends it sending to the client:

    public class MyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            /*If something happens*/
            if (/*Condition*/)
            {
                filterContext.HttpContext.Response.Write("some value here");
                filterContext.HttpContext.Response.End();
            }
    
            base.OnActionExecuting(filterContext);
        }
     }