我正在开发一个asp.net mvc 3.0应用程序,它具有简单的身份验证过程.用户填写一个表单,该表单通过ajax调用发送到服务器并获得响应,但这里的问题是使用以下方法:
FormsAuthentication.SetAuthCookie(person.LoginName,false);
是不足以填充’HttpContext.Current.User’,它需要运行以下方法:
FormsAuthentication.RedirectFromLoginPage("...");
问题在于,正如我所提到的,loggin表单使用ajax表单,并使用json获取响应,因此无法重定向.
我怎么能填写’HttpContext.Current.User’?
谢谢.
更新:
[HttpPost] public ActionResult Register(Person person) { var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault(); if (q != null) { ModelState.AddModelError("","Username is repettive,try other one"); return Json(new object[] { false,this.RenderPartialViewToString("RegisterControl",person) }); } else { if (person.LoginName.ToLower() == "admin") { person.IsAdmin = true; person.IsActive = true; } da.Persons.Add(person); da.SaveChanges(); FormsAuthentication.SetAuthCookie(person.LoginName,false); return Json(new object[] { true,"You have registered successfully!" }); } }@H_404_19@
@H_404_19@
这是我最终使用的版本,它基于@ AdamTuliper-MSFT的答案.它只能在登录后立即使用,但在重定向之前,允许其他代码访问HttpContext.User.
>如果已经过身份验证,请不要做任何事情
>不修改cookie,因为这应仅用于此请求的生命周期
>缩短一些东西,用userdata更安全一些(永远不应该为null,但……)
在调用SetAuthCookie()后调用此方法,如下所示:
// in login function FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe); AuthenticateThisRequest(); private void AuthenticateThisRequest() { //NOTE: if the user is already logged in (e.g. under a different user account) // then this will NOT reset the identity information. Be aware of this if // you allow already-logged in users to "re-login" as different accounts // without first logging out. if (HttpContext.User.Identity.IsAuthenticated) return; var name = FormsAuthentication.FormsCookieName; var cookie = Response.Cookies[name]; if (cookie != null) { var ticket = FormsAuthentication.Decrypt(cookie.Value); if (ticket != null && !ticket.Expired) { string[] roles = (ticket.UserData as string ?? "").Split(','); HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket),roles); } } }
编辑:删除对Request.Cookies的调用,如@ AdamTuplier-MSFT所述.
@H_404_19@ 原文链接:https://www.f2er.com/ajax/160148.html