views:

385

answers:

1

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

  • Let a base controller check for the type of the ActionResult.
  • If the ActionResult is a ViewResult, load some shared data for all views.
  • If the shared data fulfills some specific criteria, redirect to a login page.

How would you implement that?


I thought about the following, but it seems the redirect does not work (due to the action has already been executed?). Is there a way 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");
    }
}
A: 

I think I found an answer by trying this:

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

It works.

Ole Lynge