Cookie过期后,asp.net mvc3重定向用户

时间:2012-08-10 14:33:03

标签: asp.net asp.net-mvc-3

我有这个问题。当用户登录时,我使用formsauthanticationticket创建cookie:

var formAuthTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, "");
                    var encryptedFormAuthTicket = FormsAuthentication.Encrypt(formAuthTicket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedFormAuthTicket);
                    Response.Cookies.Add(cookie);
                    return RedirectToAction("Index", "Home");

现在。在PreRequestHandlerExecute事件中,我检查,如果用户已经过身份验证/ cookie存在。

var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (cookie != null)
        {

            var formAuthTicket = FormsAuthentication.Decrypt(cookie.Value);
            var newFormAuthTicket = new FormsAuthenticationTicket(formAuthTicket.Version, formAuthTicket.Name,
                                                                    formAuthTicket.IssueDate,
                                                                    DateTime.Now.AddMinutes(1),
                                                                    formAuthTicket.IsPersistent,
                                                                    formAuthTicket.UserData,
                                                                    FormsAuthentication.FormsCookiePath);
            cookie.Value = FormsAuthentication.Encrypt(newFormAuthTicket);
            context.Response.Cookies.Set(cookie);
        }

但是当cookie不存在/过期时,我想将用户重定向到登录页面,当他点击某个链接时。任何的想法? 感谢

修改

因为我无法使用Authorize属性。我知道。我在汇编中有httpmodule,在web项目中引用。在httpmodule中我有Init方法,我在其中初始化PreRequestHandlerExecute()事件。如果我检查用户的身份验证。如果我在“else”中使用这样的东西 - > Response.Redirect(url),发生循环重定向,这是错误的。在没有任何请求的情况下10分钟后,用户点击一些链接,他将被重定向到登录页面 - >这是我的问题,我无法解决。

1 个答案:

答案 0 :(得分:1)

为什么你不使用[Authorize]属性?添加到您的操作的标志中,如果与身份验证相关的cookie将自动重定向到登录页面

例如

[Authorize]
public ActionResult Profile()    
{
}

如果您需要创建自定义实现,您的自定义属性会实现接口,例如

public class FooAuthorizeAttribute : AuthorizeAttribute
{
     public string fooField{ get; set; }

public override void OnAuthorization(AuthorizationContext filterContext)
{
    //Do my stuff
}

然后在你的行动中调用

[FooAuthorizeAttribute]
public ActionResult Profile()    
{
}