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

Page.CurrentUser

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


当前回答

在Asp.net Mvc Identity 2中,你可以通过以下方式获取当前用户名:

var username = System.Web.HttpContext.Current.User.Identity.Name;

其他回答

用户名:System.Web.HttpContext.Current.User.Identity.Name

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

你可以使用以下代码:

Request.LogonUserIdentity.Name;

使用System.Security.Principal.WindowsIdentity.GetCurrent () . name。

这将获取当前登录的Windows用户。

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));