zoukankan      html  css  js  c++  java
  • ASP.NET MVC判断基于Cookie的Session过期

    当我们第一次请求访问时,可以看到Response的Set-Cookie里添加了ASP.NET_SessionId的值,以后再访问时可以看到Resquest里的Cookie已经包含这个Key.

    image image

    Session的IsNewSession可以判断这次请求是否第一次访问, 所以如果是第一次访问而且cookie里包含ASP.NET_SessionId,那么可以判断Session已经过期

    因此我们可以写一个如下的一个Filter加在需要判断过期的Action上,当然如果所有Action都需要处理我们可以让所有的Controller集成一个BaseController,在BaseController的OnActionExecuting方法里做, 请参考如下代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public class SessionTimeOutFilterAttribute : ActionFilterAttribute
    {
       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
           HttpContextBase ctx = filterContext.HttpContext;
           if (ctx.Session != null)
           {
               if (ctx.Session.IsNewSession)
               {
                   string sessionCookie = ctx.Request.Headers["Cookie"];
                   if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                   {
                       ctx.Response.Redirect("~/Search/Index");
                   }
               }
           }
           base.OnActionExecuting(filterContext);
       }
    }
  • 相关阅读:
    【洛谷 1546】最短网络
    [Algorithms]Greedy
    [Operating System]Thread Pool
    微积分——外微分形式的微积分
    Codeforce Round #548(Div2)
    Codeforce Round #544(Div3)
    Codeforce Round #545(Div2) (BCD题解)
    桶排序桶的前缀和/差分
    Codeforce Round #545(Div2)
    Codeforce Round #531(Div3)
  • 原文地址:https://www.cnblogs.com/sjqq/p/7608853.html
Copyright © 2011-2022 走看看