15
votes

I have initialized method in my base controller class which is called whenever any action method is executed. On every action method, I want to check my session and if it is null it should redirect to the login page.

 public class BaseController : Controller
{
    protected IDataRepository _appData = new DataRepository();

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        if (SessionFactory.CurrentAdminUser == null)
        {
            RedirectToLogin();
        }
    }
 }
public ActionResult RedirectToLogin()
    {
        return RedirectToAction("AdminLogin", "Admin");
    }

it's calling this method but not redirecting to admin login method and keeps execution on and call method which is in flow so error will come.

In short i want to check whenever my application session gets null its should rediect to login page and its not convenient to check on all methods.please suggest me some good way.

2

2 Answers

23
votes

You're calling RedirectToLogin() which in turn simply returns a RedirectToActionResult that is not being used and does not affect the flow of the action.

Try this instead:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting();

    if (SessionFactory.CurrentAdminUser == null)
        filterContext.Result = new RedirectResult(Url.Action("AdminLogin", "Admin"));
}

Alternatively, if you insist on overriding Initialize:

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);

    if (SessionFactory.CurrentAdminUser == null)
    {
        requestContext.HttpContext.Response.Clear();
        requestContext.HttpContext.Response.Redirect(Url.Action("AdminLogin", "Admin"));
        requestContext.HttpContext.Response.End();
    }
}

Also, check the [Authorize] filter, it may better suit your needs. See here.

2
votes

A simpler approach:

public void RedirectToLogin()
{
    RedirectToAction("AdminLogin", "Admin").ExecuteResult(this.ControllerContext);
}