在表单模型中,我曾经通过以下方式获取当前登录用户:

Page.CurrentUser

如何在ASP中获得控制器类中的当前用户。净MVC吗?


当前回答

IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");

其他回答

不管怎样,在ASP中。NET MVC 3你可以使用User来返回当前请求的用户。

var ticket = FormsAuthentication.Decrypt(
                    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

if (ticket.Expired)
{
    throw new InvalidOperationException("Ticket expired.");
}

IPrincipal user =  (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));

如果有人还在读这篇文章,我用下面的方式访问cshtml文件。

<li>Hello @User.Identity.Name</li>

我使用:

Membership.GetUser().UserName

我不确定这是否适用于ASP。NET MVC,但它值得一试:)

我们可以使用下面的代码在ASP中获取当前登录的用户。Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'