我有这个问题。当用户登录时,我使用 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 分钟后,用户点击了某个链接,他将被重定向到登录页面 -> 那是我的问题,我无法解决。