Redirect from Controller Initialize not working

Zaak picture Zaak · Nov 22, 2011 · Viewed 8.3k times · Source

I have override for controller that checks if certain session data exists. This data is required for repository to work properly so if it does not exist then after the check the user should be logged off.

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    if (Session["CompanyID"] != null)
    {
        repo.CompanyID = (long)Session["CompanyID"];
    }
    else
    {
        RedirectToAction("LogOff", "Account");
    }
}

My code looks like this, but even when the RedirectToAction is invoked the controller still opens the default action and the user is not logged off. Can You recommend on how to handle this problem?

I am using this session data in such a way because this is the first place i can get to it i know of and here i can check if this particular data exists. It is written when user logs in.

This data is a part of User in database. I have made a custom membership and roles provider. Is there a way to add this data to "User" of MembershipUser type somehow so it can be accessed in constructor like users username?

Answer

Rich O'Kelly picture Rich O'Kelly · Nov 22, 2011

Consider using a custom ActionFilter instead.

public class HasCompanyIdAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["CompanyID"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {action = "LogOff", controller = "Account"}));
        }
    }
}

It can then be applied as so:

[HasCompanyId]
public class MyController : Controller 
{
    public ActionResult SomeAction()
    {
        return View();
    }
}

This will apply the attribute for all requests that MyController (or it's subclasses) handles.