【问题标题】:MVC3: C# Forms Authentication and Session StateMVC3:C# 表单身份验证和会话状态
【发布时间】:2012-05-08 23:42:07
【问题描述】:

我想知道在 MVC 中处理和实现会话超时的最佳方法。我已经设置了我的应用程序,以便在用户进行身份验证时它可以处理“RememberMe”。我还在Context.Session["myvar"];中存储了一些变量

当我的会话已过期但我的身份验证 cookie 尚未过期时,我遇到了问题。

我的第一个想法是根据操作请求检查会话统计信息;但这似乎是很多代码。有没有一个检查会话状态的好地方?处理会话超时的其他方法是什么?我希望在会话超时时将用户重定向到登录页面。或者如果用户仍然登录,则重新加载会话变量。

【问题讨论】:

    标签: c# asp.net-mvc session-state


    【解决方案1】:

    有没有检查一次会话状态的好地方

    当然,自定义 Authorize 属性看起来是个好地方:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authroized = base.AuthorizeCore(httpContext);
            if (!authroized)
            {
                // the user is not authenticated or the forms authentication
                // cookie has expired
                return false;
            }
    
            // Now check the session:
            var myvar = httpContext.Session["myvar"];
            if (myvar == null)
            {
                // the session has expired
                return false;
            }
    
            return true;
        }
    }
    

    【讨论】:

    • 我将如何使用该属性?我是否将所有操作放在首位?
    • 是的,您只需将当前使用的[Authorize] 属性替换为[MyAuthorize] 属性(显然发现它是一个比MyAuthorize 更有意义的名称:-))。
    • 顺便说一句,您可以将此类放在项目中的任何位置,因为 C# 不关心文件夹,只需将 [Authorize] 标记替换为 [MyAuthorizeAttribute] 如上所述,使用适当的对命名空间的引用。
    【解决方案2】:

    在 global.asax.cs 中你可以添加 SessionStart 处理程序

    protected void Session_Start(object sender, EventArgs e)
    {
        if (this.Context.User != null && this.Context.User.Identity != null
            && this.Context.User.Identity.IsAuthenticated)
        {
            // Got user from authentication cookie (remember me).
    
            // here you can either re-instantiate user in your application/session
            // so he/she will be logged-in automatically (which is remember me functionality)
            // The username is in this.Context.User.Identity.Name
    
            // Or redirect user to login page if you need manual login
        }
    }
    

    【讨论】:

    • 但是存储在会话变量中的任何内容都会丢失,对吧?
    • @Faiz:是的,它会丢失,因为这是新会话的开始。
    猜你喜欢
    • 2011-10-09
    • 2014-07-09
    • 1970-01-01
    • 2012-02-09
    • 2010-09-26
    • 1970-01-01
    • 2013-10-22
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多