![](/img/trans.png)
[英]MVC 5: How Does Application_PostAuthenticateRequest() get called in Global.asax?
[英]How do I reference the HttpContext.Current.User after the Application_PostAuthenticateRequest in MVC?
所以这里是我的问题的步骤分解:
现在我的问题是,既然我设置了使用该网站的当前用户是谁,我该如何引用它们? 后验证完成后,我检查当前用户,它为空。 我应该将原理设置为 HttpContext.Current.User 以外的其他变量吗?
打回来
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
...
// Get roles for current user
string roles = "bob,adminbob,cthulu";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
loginInfo.Email,
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
false,
roles,
FormsAuthentication.FormsCookiePath);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(authCookie);
...
}
在 Global.asax 中进行后验证
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) {
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] userRoles = authTicket.UserData.Split(new Char[] { ',' });
GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), userRoles);
HttpContext.Current.User = userPrincipal; //How do I reference this in the program?
}
}
没关系我想出了为什么它返回空白。 当我调用方法来检查 Name 时,Identity 尚未通过身份验证。 如果您尝试在未经过身份验证的情况下获取名称,则会返回空白。
所以我只是简单地检查:
HttpContext.Current.User.Identity.IsAuthenticated
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.