【问题标题】:ASP.NET MVC 3 determine session status (new or timeout)ASP.NET MVC 3 确定会话状态(新的或超时)
【发布时间】:2012-01-03 08:47:16
【问题描述】:

我目前对我的 ASP.NET MVC 应用程序使用默认的表单身份验证方法。

在我所有需要身份验证的操作方法中,我都有这个属性

[Authorize()]

当有人试图调用该操作方法“服务”的页面并且他们尚未登录时,它会将他们发送到登录页面......完美!但是,如果他们的会话超时并且他们试图访问该页面,他们也只是被重定向到登录页面,而没有说明原因。我希望能够确定是新访问还是超时,并相应地在登录屏幕上显示不同的消息。

这可能吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 session forms-authentication


    【解决方案1】:

    看看我创建的这个自定义授权属性。这是为了实现一些基于自定义角色的授权,但你也可以让它为你工作。有一个 Session.IsNewSession 属性,您可以检查此请求是否发生在新会话上。

    public class CustomAuthorizeAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                if (httpContext.User.Identity.IsAuthenticated)
                {
                    httpContext.User = new GenericPrincipal(httpContext.User.Identity, AdminUserViewModel.Current.SecurityGroups.Select(x => x.Name).ToArray());
                }
                return base.AuthorizeCore(httpContext);
            }
    
            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.Result = new RedirectResult("/Authentication/NotAuthorized", false);
                }
                else
                {
                    if (filterContext.HttpContext.Session.IsNewSession)
                    {
                        // Do Something For A New Session
                    }
                    base.HandleUnauthorizedRequest(filterContext);
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

      登录时,您可以设置与浏览器会话相关的 cookie。如果该 cookie 存在,您就知道会话已超时。如果没有,你知道这是一次新的访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 2017-07-30
        • 2011-08-12
        • 1970-01-01
        相关资源
        最近更新 更多