1

First of all I have already look at the similar solution to the following ones:

ASP.NET MVC : Handle Session Expire Using Custom Attribute

Redirect to specific page after session expires (MVC4)

But I need a smart solution regarding to this problem by just typing a code on Global.asax etc. and not requiring an extra implementation on every Cntroller. Is it possible? If not, what is the best approach for redirecting to login page after session is timeout in ASP.NET MVC?

Community
  • 1
  • 1
Jack
  • 1
  • 21
  • 118
  • 236
  • I recommend you Use Custom Attribute. – rootturk Dec 30 '16 at 10:35
  • @AkınAbdullahoğlu Why do not post any example that you had used before? – Jack Dec 30 '16 at 10:38
  • My idea is not to use global.asax, this example will give an idea https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters – rootturk Dec 30 '16 at 10:55
  • In that case the way on http://www.c-sharpcorner.com/UploadFile/91c28d/handle-session-expire-using-custom-attribute-in-Asp-Net-mvc/ page is good for me, is not it? – Jack Dec 30 '16 at 11:01
  • I added Sample. – rootturk Jan 02 '17 at 08:55
  • Just make it a Global Attribute and you don't have to apply it to every controller ([asp.net-mvc-6](http://stackoverflow.com/questions/31237613/how-to-register-a-global-filter-with-mvc-6-asp-net-5) or `GlobalFilters.Filters.Add(new MyActionFilterAttribute());` for previous versions.) – Erik Philips Jan 02 '17 at 17:33
  • @ErikPhilips I have tried many examples as on [Redirect to login Page after session timeout in MVC 5](https://forums.asp.net/t/2041070.aspx?Redirect+to+login+Page+after+session+timeout+in+MVC+5) but it did not make any sense. Normally the code hits the implemented method, but after sesion expired the code does not hit neither Controller not the implemented method even if I remove [Authorize] attribute. Maybe it is mostly related to AJAX and after session is timeout AJAX might not pots request to Controller. If not, why the code does not hit to the Controller method? Any idea? How to fix it? – Jack Jan 05 '17 at 06:39

4 Answers4

0

You can handle session timeouts in Global.asax from Session_End method. Just FYI, It has some cons: it will be called not necessarily right after the timeout and it works if your session is in runtime memory. Try it, maybe it will be enough for your case.

Another way to do it can be using SessionStateModule or creation custom HTTP module paired with some of global events which can be used for session control.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
ivamax9
  • 2,601
  • 24
  • 33
  • Could you please post an example indicating how to integrate them to an existing ASP.MVC project? – Jack Dec 30 '16 at 10:40
  • for the first case just copy logic from SO answers that you have mentioned, for the second case you can check answer of user1429080 because he is using global events (his event is appearing when the request state (for example, session state) that is associated with the current request has been obtained) – ivamax9 Dec 30 '16 at 11:07
  • Not worked for me. I load page using partialview via AJAX and this approach not worked (the code does not hit to here when session is expired) :( Any idea? – Jack Jan 02 '17 at 14:55
  • yeah, so in your case it should be handled via javascript (you can check some response headers, which you can set by the backend, and make a redirect to login page if ajax response has these headers). which identity provider are you using? something custom? – ivamax9 Jan 02 '17 at 15:44
  • I use ASP.NET Identity 2.0. Could you please post or suggest an example with Javascript? Thanks... – Jack Jan 03 '17 at 09:11
0

Tested this with a freshly setup MVC application. The idea behind it, which is to inspect the state of the session for each incoming request seems to work correctly in my case.

void Application_PostAcquireRequestState(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    if (context.Session != null)
    {
        if (context.Session["sessionExist"] is bool && (bool)context.Session["sessionExist"])
            return;
    }

    // put code here that you want to execute if the session has expired
    // for example:

    FormsAuthentication.SignOut();

    // or maybe

    context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}

Then add Session["sessionExist"] = true; after a user is successfully logged in.

user1429080
  • 9,086
  • 4
  • 31
  • 54
  • No, it cause the applicat6ion give error. I think not suitable for ASP.NET MVC. – Jack Jan 02 '17 at 14:55
  • @ClintEastwood Try the edited version without the explicit redirect to login page. The redirect might cause problems if it fails to correctly identify the login page in the preceding `if` clause. If that still does not work for you, I'll remove the answer... – user1429080 Jan 02 '17 at 17:27
  • I think the approach is ok, but there seems to be a little missing point. I use AJAX for opening page (rendering partialview) and this method cannot redirect to Login page. How to fix it? There is no need to delete your answer, just edit it. Thanks... – Jack Jan 03 '17 at 09:13
0

Use GlobalFilters in global.asax

GlobalFilters.Filters.Add(new SessionExpireFilterAttribute());

Reference taken from best answer's comment by Dean Ward Redirect to specific page after session expires (MVC4)

Community
  • 1
  • 1
Saad Suri
  • 1,352
  • 1
  • 14
  • 26
  • Thanks, it seems to be good solution but unfortunately Not worked for me. I load page using partialview via AJAX and this approach not worked (the code does not hit to here when session is expired) :( Any idea? – Jack Jan 02 '17 at 14:54
  • Then you need to make it by yourself. you need to make a timer in c# and and when the timer hits at the right the right time kill all session. @ClintEastwood – Saad Suri Jan 04 '17 at 01:38
0

I often see such solutions your example : http://www.c-sharpcorner.com/UploadFile/91c28d/handle-session-expire-using-custom-attribute-in-Asp-Net-mvc/

Before you can Create BaseController.cs Controller and define OnActionExecuting Method.

public class BaseController : Controller
{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        base.OnActionExecuting(filterContext);


        if (Session["UserLogin"] == null)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "ManageAccount" }, { "action", "Login" } });
        }
    }

}

In the next step Create HomeController.cs inherited BaseController.cs file.

public class HomeController : BaseController
{
    // GET: Home
    public ActionResult Index()
    {  
        return View();
    }
}

BaseController OnActionExecuting method handled every request and check session control.

    [HttpPost]
    public ActionResult LoggedIn()
    {
        Session["UserLogin"] = true;

        return RedirectToAction("Index", "Home");
    }

Create example login post method, send request set UserLogin session parameter and redirect to Home/Index page.. Each controller that you inherit calls will perform session control for each request.

I Hope it helps.

rootturk
  • 316
  • 4
  • 20
  • Not worked for me. I load page using partialview via AJAX and this approach not worked (the code does not hit to here when session is expired) :( Any idea? – Jack Jan 02 '17 at 14:54