简体   繁体   中英

How to get the current user 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?

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 .

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

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

您可以像这样在 ASP.NET MVC4 中获取用户的名称:

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

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.

I use:

Membership.GetUser().UserName

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

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

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'

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;

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();

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

You just need User.Identity.Name .

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

This will get the current logged-in Windows user.

您可以使用以下代码:

Request.LogonUserIdentity.Name;

值得一提的是,在 ASP.NET MVC 3 中,您只需使用 User 即可返回当前请求的用户。

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

MembershipUser u = Membership.GetUser(LoginUser.UserName);
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));

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

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

var username = System.Web.HttpContext.Current.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;

如果有人仍在阅读此内容,请以以下方式访问我使用的 cshtml 文件。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM