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'
// 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...
您必须在以下内容中包含与“活动目录上下文”有关的任何调用,以便它充当获取AD信息的托管环境:
using (HostingEnvironment.Impersonate()){ ... }
您还必须在web.config中将 impersonate 设置为true:
<system.web>
<identity impersonate="true" />
您必须在web.config中启用Windows身份验证:
<authentication mode="Windows" />
36
试试 HttpContext.Current.User .
Public Shared Property Current()As System.Web.HttpContext System.Web.HttpContext的成员摘要:获取或设置当前HTTP请求的System.Web.HttpContext对象 . 返回值:当前HTTP请求的System.Web.HttpContext
我发现 User 有效,即 User.Identity.Name 或 User.IsInRole("Administrator") .
4
我用:
Membership.GetUser().UserName
我不确定它在ASP.NET MVC中是否可行,但它值得一试:)
4
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));
19 回答
我们可以使用以下代码来获取ASP.Net MVC中当前登录的用户:
也
您可以在ASP.NET MVC4中获取用户的名称,如下所示:
值得一提的是,在ASP.NET MVC 3中,您可以使用User来返回当前请求的用户 .
如果您在登录页面内,例如在LoginUser_LoggedIn事件中,Current.User.Identity.Name将返回一个空值,因此您必须使用yourLoginControlName.UserName属性 .
在Asp.net Mvc Identity 2中,您可以通过以下方式获取当前用户名:
您可以使用以下代码:
如果您恰好在Intranet上的Active Directory中工作,请参阅以下提示:
(Windows Server 2012)
在Web服务器上运行与AD对话的任何内容都需要大量的更改和耐心 . 因为当在Web服务器上运行而不是本地IIS / IIS Express时,它以AppPool的身份运行,因此,您必须将其设置为模拟访问该站点的任何人 .
当ASP.NET MVC应用程序在网络内的Web服务器上运行时,如何将当前登录用户置于活动目录中:
您必须在以下内容中包含与“活动目录上下文”有关的任何调用,以便它充当获取AD信息的托管环境:
您还必须在web.config中将
impersonate
设置为true:您必须在web.config中启用Windows身份验证:
试试
HttpContext.Current.User
.这个页面可能是你要找的:
Using Page.User.Identity.Name in MVC3
你只需要
User.Identity.Name
.使用
System.Security.Principal.WindowsIdentity.GetCurrent().Name
.这将获得当前登录的Windows用户 .
用户名:
但是,如果您只需要获取ID,则可以使用:
因此,您可以直接获得用户ID:
如果需要从控制器中获取用户,请使用Controller的
User
属性 . 如果您从视图中需要它,我会在ViewData
中填充您特别需要的内容,或者您可以调用User,因为我认为它是ViewPage
的属性 .我意识到这已经很老了,但我刚刚开始使用ASP.NET MVC,所以我想我会坚持两分钱:
Request.IsAuthenticated
告诉您用户是否经过身份验证 .Page.User.Identity
为您提供登录用户的身份 .登录用户名:
System.Web.HttpContext.Current.User.Identity.Name
我发现
User
有效,即User.Identity.Name
或User.IsInRole("Administrator")
.我用:
我不确定它在ASP.NET MVC中是否可行,但它值得一试:)
为了在控制器中引用在ASP.NET MVC 4中内置的简单身份验证创建的用户ID,以便进行过滤(如果您首先使用数据库而实体框架5生成代码优先绑定并且您的表的结构是如此,这将非常有用使用了userID的外键),你可以使用
一旦添加了using语句