我有一个最近从 MVC 4 迁移过来的 ASP.Net MVC 5 项目。我正在使用 FormsAuthentication 和 HTTPS 和匿名身份验证,并使用它设置一个 cookie:
FormsAuthentication.RedirectFromLoginPage(用户名, false)
身份验证有效,但我遇到的问题是在我的 C# 代码中获取当前用户的名称。在我看来,我可以很好地掌握它,
User.Identity.GetUserName()
但我无法在 Controller 中获取它。 HttpContext.CurrentUser
不存在,并且 Controller 中的 this.User
始终为 null。我也尝试过请求 cookie,但失败了。
我是否必须在他们登录时自行设置身份?我可能需要用户名册,但我总是可以查询数据库来获取它们。
简而言之,如何在 MVC 5 的 Controller 中获取当前用户的用户名?谢谢
最佳答案
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!
关于c# - ASP.Net MVC 5 Forms Authentication 在代码后面获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049292/