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

Page.CurrentUser

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


当前回答

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

其他回答

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

这个页面可能就是你要找的: 在MVC3中使用Page.User.Identity.Name

你只需要User.Identity.Name。

我们可以使用下面的代码在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'

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

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

如果你在登录页面中,以LoginUser_LoggedIn事件为例,Current.User.Identity.Name将返回一个空值,所以你必须使用yourLoginControlName。用户名属性。

MembershipUser u = Membership.GetUser(LoginUser.UserName);