在剃刀中获取当前用户名

问题描述 投票:5回答:2

我想在剃刀视图页面中获取当前经过身份验证的用户名,因此我使用了

if (User.Identity.IsAuthenticated)
{
      <p>Name is @User.Identity.Name</p>
}

但@ User.Identity.Name始终显示用户的ID。

asp.net-mvc-4 razor
2个回答
8
投票

试试这个(MVC):

@{ var userName = System.Web.HttpContext.Current.User.Identity.Name; }

-1
投票

在FormsAuthentication中,您必须提供用户名。我认为您在表单身份验证中提供用户的ID而不是用户名。

请执行以下代码以创建身份验证。

var authTicket = new FormsAuthenticationTicket(1, **UserName**, DateTime.Now, DateTime.Now.AddMinutes(30), true, Role);
string cookieContents = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
{
    Expires = authTicket.Expiration,
    Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
© www.soinside.com 2019 - 2024. All rights reserved.