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

StackOverflow https://stackoverflow.com/questions/18411465

Question

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

Was it helpful?

Solution 2

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);
    }
 }

OTHER TIPS

Yes, it is possible. You can set the result of the filter context provided to you when overriding OnActionExecuting in ActionFilterAttribute.

using System.Web.Mvc;

public sealed class SampleFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting( ActionExecutingContext filterContext )
    {
        filterContext.Result = new RedirectResult( "http://google.com" );
    }
}

In the source, you can see that setting the Result property of the filter context changes the flow.

From System.Web.Mvc.ControllerActionInvoker:

internal static ActionExecutedContext InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func<ActionExecutedContext> continuation)
{
    filter.OnActionExecuting(preContext);
    if (preContext.Result != null)
    {
        return new ActionExecutedContext(preContext, preContext.ActionDescriptor, true /* canceled */, null /* exception */)
        {
            Result = preContext.Result
        };
    }

    // other code ommitted
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top