Snæbjørn
Snæbjørn

Reputation: 10792

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

Upvotes: 1

Views: 1295

Answers (2)

Snæbjørn
Snæbjørn

Reputation: 10792

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

Upvotes: 2

dwbartz
dwbartz

Reputation: 886

ActionExecutedContext has an ActionResult. You could check whether the ActionResult is a ViewResult or RedirectResult/RedirectToRouteResult in your OnActionExecuted.

Upvotes: 0

Related Questions