如何在 ASP.NET MVC 中获取当前用户

发布于 2024-07-08 13:07:27 字数 156 浏览 7 评论 0原文

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

Page.CurrentUser

How do I get the current user inside a controller class in ASP.NET MVC?

In a forms model, I used to get the current logged-in user by:

Page.CurrentUser

How do I get the current user inside a controller class in ASP.NET MVC?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

私藏温柔 2024-07-15 13:07:28

在Asp.net Mvc Identity 2中,您可以通过以下方式获取当前用户名:

var username = System.Web.HttpContext.Current.User.Identity.Name;

In Asp.net Mvc Identity 2,You can get the current user name by:

var username = System.Web.HttpContext.Current.User.Identity.Name;
我做我的改变 2024-07-15 13:07:28

如果有人仍在阅读本文,请按照以下方式访问 cshtml 文件。

<li>Hello @User.Identity.Name</li>

If any one still reading this then, to access in cshtml file I used in following way.

<li>Hello @User.Identity.Name</li>
不知所踪 2024-07-15 13:07:28

在 IIS 管理器的“身份验证”下,禁用:
1) 匿名认证
2) 表单身份验证

然后将以下内容添加到您的控制器中,以处理测试与服务器部署:

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;

In the IIS Manager, under Authentication, disable:
1) Anonymous Authentication
2) Forms Authentication

Then add the following to your controller, to handle testing versus server deployment:

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;
染柒℉ 2024-07-15 13:07:27

如果您需要从控制器内获取用户,请使用控制器的User属性。 如果您需要从视图中获取它,我会在 ViewData 中填充您特别需要的内容,或者您​​可以直接调用 User,因为我认为它是 ViewPage 的属性。

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData, or you could just call User as I think it's a property of ViewPage.

自由范儿 2024-07-15 13:07:27

我发现 User 有效,即 User.Identity.NameUser.IsInRole("Administrator")

I found that User works, that is, User.Identity.Name or User.IsInRole("Administrator").

小糖芽 2024-07-15 13:07:27

尝试HttpContext.Current.User

公共共享属性 Current() As
System.Web.HttpContext
System.Web.HttpContext 的成员

摘要:
获取或设置当前 HTTP 请求的 System.Web.HttpContext 对象。

返回值:
当前的 System.Web.HttpContext
HTTP 请求

Try HttpContext.Current.User.

Public Shared Property Current() As
System.Web.HttpContext
Member of System.Web.HttpContext

Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.

Return Values:
The System.Web.HttpContext for the current
HTTP request

未蓝澄海的烟 2024-07-15 13:07:27

您可以在 ASP.NET MVC4 中获取用户名,如下所示:

System.Web.HttpContext.Current.User.Identity.Name

You can get the name of the user in ASP.NET MVC4 like this:

System.Web.HttpContext.Current.User.Identity.Name
小巷里的女流氓 2024-07-15 13:07:27

我意识到这确实很旧,但我刚刚开始使用 ASP.NET MVC,所以我想我应该把我的两分钱放在:

  • Request.IsAuthenticated 告诉您用户是否经过身份验证。
  • Page.User.Identity 为您提供登录用户的身份。

I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:

  • Request.IsAuthenticated tells you if the user is authenticated.
  • Page.User.Identity gives you the identity of the logged-in user.
独行侠 2024-07-15 13:07:27

我使用:

Membership.GetUser().UserName

我不确定这是否适用于 ASP.NET MVC,但值得一试:)

I use:

Membership.GetUser().UserName

I am not sure this will work in ASP.NET MVC, but it's worth a shot :)

迷路的信 2024-07-15 13:07:27

登录用户名:System.Web.HttpContext.Current.User.Identity.Name

getting logged in username: System.Web.HttpContext.Current.User.Identity.Name

箜明 2024-07-15 13:07:27

UserName with:

User.Identity.Name

但如果你只需要获取ID,你可以使用:

using Microsoft.AspNet.Identity;

所以,你可以直接获取User ID:

User.Identity.GetUserId();

UserName with:

User.Identity.Name

But if you need to get just the ID, you can use:

using Microsoft.AspNet.Identity;

So, you can get directly the User ID:

User.Identity.GetUserId();
-柠檬树下少年和吉他 2024-07-15 13:07:27

为了引用在控制器中使用内置于 ASP.NET MVC 4 的简单身份验证创建的用户 ID 以进行过滤(如果您首先使用数据库和实体框架 5 来生成代码优先绑定,并且您的表的结构如下,这会很有帮助)使用了 userID 的外键),

WebSecurity.CurrentUserId

一旦添加 using 语句就可以使用

using System.Web.Security;

In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use

WebSecurity.CurrentUserId

once you add a using statement

using System.Web.Security;
枫以 2024-07-15 13:07:27

我们可以使用以下代码来获取 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'

We can use following code to get the current logged in User in ASP.Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

Also

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'
后eg是否自 2024-07-15 13:07:27

此页面可能就是您要寻找的内容:
在 MVC3 中使用 Page.User.Identity.Name

你只需要 <代码>用户.身份.名称。

This page could be what you looking for:
Using Page.User.Identity.Name in MVC3

You just need User.Identity.Name.

倾城°AllureLove 2024-07-15 13:07:27

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

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

Use System.Security.Principal.WindowsIdentity.GetCurrent().Name.

This will get the current logged-in Windows user.

抚笙 2024-07-15 13:07:27

不管怎样,在 ASP.NET MVC 3 中,您可以只使用 User 来返回当前请求的用户。

For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.

惜醉颜 2024-07-15 13:07:27

如果您在登录页面内,例如在 LoginUser_LoggedIn 事件中,Current.User.Identity.Name 将返回空值,因此您必须使用 yourLoginControlName.UserName 属性。

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

If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.

MembershipUser u = Membership.GetUser(LoginUser.UserName);
仙气飘飘 2024-07-15 13:07:27
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");
IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");
像极了他 2024-07-15 13:07:27

您可以使用以下代码:

Request.LogonUserIdentity.Name;

You can use following code:

Request.LogonUserIdentity.Name;
天冷不及心凉 2024-07-15 13:07:27
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));
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));
一张白纸 2024-07-15 13:07:27

如果您碰巧在 Intranet 上的 Active Directory 中工作,这里有一些提示:

(Windows Server 2012)

在 Web 服务器上运行任何与 AD 通信的内容都需要大量的更改和耐心。 由于在 Web 服务器上运行时与本地 IIS/IIS Express 上运行时,它以 AppPool 的身份运行,因此您必须将其设置为模拟访问该站点的任何人。

当 ASP.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...

您必须将与“活动目录上下文”相关的所有调用包装在下面,以便它起作用作为获取 AD 信息的托管环境:

using (HostingEnvironment.Impersonate()){ ... }

您还必须在 web.config 中将 impersonate 设置为 true:

<system.web>
    <identity impersonate="true" />

您必须在 web.config 中启用 Windows 身份验证:

<authentication mode="Windows" />

If you happen to be working in Active Directory on an intranet, here are some tips:

(Windows Server 2012)

Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.

How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:

// 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...

You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:

using (HostingEnvironment.Impersonate()){ ... }

You must also have impersonate set to true in your web.config:

<system.web>
    <identity impersonate="true" />

You must have Windows authentication on in web.config:

<authentication mode="Windows" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文