在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
当前回答
这个页面可能就是你要找的: 在MVC3中使用Page.User.Identity.Name
你只需要User.Identity.Name。
其他回答
您可以在ASP中获取用户名。NET MVC4:
System.Web.HttpContext.Current.User.Identity.Name
我使用:
Membership.GetUser().UserName
我不确定这是否适用于ASP。NET MVC,但它值得一试:)
如果有人还在读这篇文章,我用下面的方式访问cshtml文件。
<li>Hello @User.Identity.Name</li>
我发现User工作,即User. identity . name或User. isinrole(“管理员”)。
如果你碰巧在内部网的Active Directory中工作,这里有一些提示:
(Windows Server 2012)
在web服务器上运行任何与AD对话的程序都需要大量的更改和耐心。因为当运行在web服务器上而不是本地IIS/IIS Express时,它运行在AppPool的身份中,所以你必须设置它来模拟任何访问站点的人。
如何在活动目录中获取当前登录的用户。NET MVC应用程序运行在网络内的web服务器上:
// Find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
//Then work with 'adUser' from here...
你必须在下面包装任何与'active directory context'有关的调用,这样它就充当了宿主环境来获取AD信息:
using (HostingEnvironment.Impersonate()){ ... }
你还必须在你的web.config中将impersonate设置为true:
<system.web>
<identity impersonate="true" />
在web.config中必须开启Windows身份验证:
<authentication mode="Windows" />