在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
当前回答
我发现User工作,即User. identity . name或User. isinrole(“管理员”)。
其他回答
如果需要从控制器内部获取用户,请使用controller的user属性。如果你从视图中需要它,我会在ViewData中填充你特别需要的东西,或者你可以只调用User,因为我认为它是ViewPage的一个属性。
如果有人还在读这篇文章,我用下面的方式访问cshtml文件。
<li>Hello @User.Identity.Name</li>
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
...
currentUser.IsInRole("Operator");
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));
在Asp.net Mvc Identity 2中,你可以通过以下方式获取当前用户名:
var username = System.Web.HttpContext.Current.User.Identity.Name;