1

I am trying to do a simple redirect to login page if session expires in asp.net mvc 4.5. I am trying it as follows.

Global.asax

protected void Session_OnEnd(object sender, EventArgs e)
{
    Response.RedirectToRoute("Default"); //default is route
} 

but here null exception comes and response object is not found. I have seen this post but could not figure out as it is pretty broad.

UPDATE

I have tried applying filter as follows now it does not crash but also does not redirect to error page.

SessionTimeoutAttribute

public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        if (HttpContext.Current.Session["SchoolCode"] == null)
        {
            filterContext.Result = new RedirectResult("~/Views/Shared/Error");
            return;
        }
        base.OnActionExecuting(filterContext);
    }

Added Attribute to Controller class

[SessionTimeout]
public class MapsController : Controller{}

Why doesnt it redirect?

Samra
  • 1,815
  • 4
  • 35
  • 71
  • What do you mean by "response object is not found" ? Did you try putting a `try...catch` around your code to check if any exception thrown? – Siva Gopal Aug 29 '17 at 06:43
  • as the answer suggests in the post you have linked, use `ActionFilters` and check for `Session` inside it. – adiga Aug 29 '17 at 08:28
  • i get An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code Additional information: Response is not available in this context. – Samra Aug 29 '17 at 23:43

1 Answers1

1

I had to change my code a little

public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        if (HttpContext.Current.Session["SchoolCode"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                                                        new { action = "Login", controller = "Account" }));                
            //return;
        }
        base.OnActionExecuting(filterContext);
    }

ignore Session_OnEnd code its no use.

Samra
  • 1,815
  • 4
  • 35
  • 71