Search code examples
c#asp.net-coreaction-filter

Check if action returned View or Redirect in ActionFitler


How do I check if an action returned View() or Redirect() in a custom ActionFilter? I need to check this as my ActionFilter populates the ViewBag with extra stuff. But if it's a redirect it is not needed.

Example

Controller Action

[MyActionFilter]
public IActionResult Index()
{
    if (ModelState.IsValid())
        return View();
    else
        return Redirect("foo");
}

Action Filter

public class MyActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // do something before the action executes
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (returned View)
            context.Controller.ViewBag.Foo = "Bar";
        else
            // do other stuff
    }
}

Solution

  • I figured it out.

    Using an ResultFilter instead gave me access to the returned type. I also had to change from the after action to the before action as changing the result in the after action generally isn't allowed.

    public class MyActionFilter : IResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ViewResult)
                context.Controller.ViewBag.Foo = "Bar";
            else
                // do other stuff
        }
    
        public void OnResultExecuted(ResultExecutedContext context)
        {
        }
    }