How can I redirect after ActionResult is defined?

In ASP.NET MVC, I would like to do something like:

  • Let the underlying controller check the type ActionResult

    .
  • If ActionResult

    is ViewResult

    , load some shared data for all views.
  • If the general data meets certain criteria, redirect it to the login page.

How do you implement this?


I thought about the following, but it looks like the redirection is not working (due to the action already taken?). Is there a way to get around this?

public abstract class BaseController : Controller
{
    protected override void OnActionExecuted
        (ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        // If the result is a view result,
        // then it loads the shared data (for use in shared view):
        if (filterContext.Result is ViewResult)
            LoadSharedData();
    }

    private void LoadSharedData()
    {
        // TODO: Loads the data that is common for all views.
        // TODO: If the shared data fulfills some specific criteria,
        //       it will redirect to a login page.
        Redirect("http://someurl");
    }
}

      

0


a source to share


1 answer


I think I found the answer by trying this:

filterContext.Result = Redirect("http://someurl");

      



He works.

0


a source







All Articles