繁体   English   中英

ASP.Net MVC 5表单身份验证获取代码后面的用户名

[英]ASP.Net MVC 5 Forms Authentication get username in code behind

我有一个ASP.Net MVC 5项目,我最近从MVC 4迁移。我正在使用FormsAuthentication与HTTPS和匿名身份验证,并使用以下设置cookie:

FormsAuthentication.RedirectFromLoginPage(Username, false)

身份验证有效,但我遇到的问题是在我的C#代码中获取当前用户的名称。 在我看来,我可以做得很好

User.Identity.GetUserName()

但是我无法在控制器中找到它。 HttpContext.CurrentUser不存在,并且控制器中的this.User始终为null。 我也尝试过请求cookie,但它失败了。

我必须在登录时自己设置身份吗? 我可能需要用户滚动,但我总是可以查询数据库来获取它们。

简而言之,如何在MVC 5中的控制器中获取当前用户的用户名? 谢谢

string cookieName = FormsAuthentication.FormsCookieName; //Find cookie name
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName]; //Get the cookie by it's name
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); //Decrypt it
string UserName = ticket.Name; //You have the UserName!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM