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));
// 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" />
4
我们可以使用以下代码来获取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'
2
您可以使用以下代码:
Request.LogonUserIdentity.Name;
3
在Asp.net Mvc Identity 2中,您可以通过以下方式获取当前用户名:
var username = System.Web.HttpContext.Current.User.Identity.Name;
19 回答
如果需要从控制器中获取用户,请使用Controller的
User
属性 . 如果您从视图中需要它,我会在ViewData
中填充您特别需要的内容,或者您可以调用User,因为我认为它是ViewPage
的属性 .我发现
User
有效,即User.Identity.Name
或User.IsInRole("Administrator")
.试试
HttpContext.Current.User
.您可以在ASP.NET MVC4中获取用户的名称,如下所示:
我意识到这已经很老了,但我刚刚开始使用ASP.NET MVC,所以我想我会坚持下去:
Request.IsAuthenticated
告诉您用户是否经过身份验证 .Page.User.Identity
为您提供登录用户的身份 .我用:
我不确定这会在ASP.NET MVC中有效,但是值得一试:)
登录用户名:
System.Web.HttpContext.Current.User.Identity.Name
为了在过滤目的中引用在ASP.NET MVC 4中内置的简单身份验证创建的用户ID(如果您首先使用数据库而实体框架5生成代码优先绑定并且您的表的结构是如此你可以使用那个用户ID的外键)
一旦添加了using语句
用户名:
但是,如果您只需要获取ID,则可以使用:
因此,您可以直接获得用户ID:
这个页面可能是你要找的:
Using Page.User.Identity.Name in MVC3
你只需要
User.Identity.Name
.使用
System.Security.Principal.WindowsIdentity.GetCurrent().Name
.这将获得当前登录的Windows用户 .
对于它的 Value ,在ASP.NET MVC 3中,您可以使用User来返回当前请求的用户 .
如果您在登录页面内,例如在LoginUser_LoggedIn事件中,Current.User.Identity.Name将返回一个空值,因此您必须使用yourLoginControlName.UserName属性 .
如果您恰好在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身份验证:
我们可以使用以下代码来获取ASP.Net MVC中当前登录的用户:
也
您可以使用以下代码:
在Asp.net Mvc Identity 2中,您可以通过以下方式获取当前用户名: