【问题标题】:How to get the current user in ASP.NET MVC如何在 ASP.NET MVC 中获取当前用户
【发布时间】:2008-11-04 21:24:25
【问题描述】:

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

Page.CurrentUser

如何在 ASP.NET MVC 的控制器类中获取当前用户?

【问题讨论】:

    标签: c# .net asp.net-mvc iis forms-authentication


    【解决方案1】:

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

    【讨论】:

    • "或者您可以直接调用 User,因为我认为它是 ViewPage 的一个属性" - 那么您的意思是在视图中使用 Page.user 吗?
    • 是的,您可以像“嗨,@User.Identity.Name!”一样使用它。在cshtml中。
    【解决方案2】:

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

    【讨论】:

    • 补充一点,如果您在表格之外的课程中工作,您需要Imports System.Web 并进一步使用HttpContext.Current.User.Identity.Name 进行限定,或者直接使用完整的限定语法:System.Web.HttpContext.Current.User.Identity.Name
    • 在 Controller 中工作,如果使用 ViewModel,要么继承自 Controller,要么遵循 Paul 的建议。
    【解决方案3】:

    试试HttpContext.Current.User

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

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

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

    【讨论】:

    • 显然 HttpContext 没有名为“Current”的属性。
    • 我相信你们两个在谈论两个不同的事情。 System.Web.HttpContext 和静态属性:System.Web.Mvc.Controller.HttpContext(没有“当前”属性。
    • 这适用于非 MVC 环境,正是我所需要的。谢谢! :)
    【解决方案4】:

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

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

    【讨论】:

    • 如果您收到此错误'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found,我建议您进行这样的绝对调用,System.Web.HttpContext.Current.User.Identity.Name
    【解决方案5】:

    我意识到这已经很老了,但我才刚刚开始使用 ASP.NET MVC,所以我想我会花上两分钱:

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

    【讨论】:

      【解决方案6】:

      我用:

      Membership.GetUser().UserName
      

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

      【讨论】:

      • 这个 Membership 类是从哪里来的?默认情况下,IntelliSense 无法识别它。
      • System.Web.Security 命名空间。我不确定这在 MVC 中是否有用,但我将它与 Web 窗体的登录控件一起使用。
      • 它在任何使用 Membership 提供程序的 ASP.NET 应用程序中都很有用。
      • 这实际上会发出一个数据库请求。 HttpContext.Current.User 没有。
      【解决方案7】:

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

      【讨论】:

        【解决方案8】:

        用户名:

        User.Identity.Name
        

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

        using Microsoft.AspNet.Identity;
        

        所以,你可以直接获取用户ID:

        User.Identity.GetUserId();
        

        【讨论】:

        • 这个方法返回一个System.Guid
        • User.Identity.Name 是 System.Security.Principal.IPrincipal 的一个实例,它没有 id 属性...此 User 与 User.Identity.GetUserId 的 User 对象不同吗跨度>
        【解决方案9】:

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

        【讨论】:

        • hi @rajbaral 这对我有用,如果我想从数据库中提取当前用户的其他信息,例如地址字段。
        • @rickyProgrammer 你需要编写一个方法来使用userName从你的广告中获取 UserProfile
        【解决方案10】:

        为了引用使用控制器中内置于 ASP.NET MVC 4 中的简单身份验证创建的用户 ID 以进行过滤(如果您使用数据库优先和 Entity Framework 5 生成代码优先绑定和表,这将很有帮助结构,以便使用用户 ID 的外键),您可以使用

        WebSecurity.CurrentUserId
        

        添加 using 语句后

        using System.Web.Security;
        

        【讨论】:

        • 不幸的是,这似乎不再适用于 MVC 5。不知道为什么 =/
        • 只有System.Security.Principal.WindowsIdentity.GetCurrent().NameMVC 5 中有效。但是,这会使用用户名提取域名。即域\用户名
        【解决方案11】:

        此页面可能是您要查找的内容:
        Using Page.User.Identity.Name in MVC3

        你只需要User.Identity.Name

        【讨论】:

        • 这只适用于控制器;或者如果您的 ViewModel 继承自 Controller
        【解决方案12】:

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

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

        【讨论】:

        • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的,并描述何时使用它。从长远来看,纯代码的答案没有用处。
        • System.Security.Principal.WindowsIdentity.GetCurrent().Name 返回当前登录到 Windows 的用户,OP 正在询问当前登录到网站的用户。
        【解决方案13】:

        对于它的价值,在 ASP.NET MVC 3 中,您可以只使用返回当前请求的用户的 User。

        【讨论】:

          【解决方案14】:

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

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

          【讨论】:

            【解决方案15】:

            您可以使用以下代码:

            Request.LogonUserIdentity.Name;
            

            【讨论】:

            • 这将为您获取运行应用程序的 AppPool 的用户名。
            【解决方案16】:
            IPrincipal currentUser = HttpContext.Current.User;
            bool writeEnable = currentUser.IsInRole("Administrator") ||
                    ...
                               currentUser.IsInRole("Operator");
            

            【讨论】:

              【解决方案17】:
              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));
              

              【讨论】:

                【解决方案18】:

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

                (Windows 服务器 2012)

                在网络服务器上运行任何与 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" />
                

                【讨论】:

                • 我不这么认为,因为这是明确使用您的 Active Directory 用户凭据。如果您希望您的用户通过 AD 进行身份验证,为什么还要使用“表单”?
                • 在我们的组织中,我们有几个工作站由几个“现场”人员共享。因此,我们需要将登录页面添加到我们的 Intranet Web 应用程序中。
                • 作为一种解决方法:您可以运行此应用程序的两个副本,一个处于“表单”模式并带有自己的身份表,或者您可以将两者混合在一个应用程序中,但这比较棘手。一个快速的谷歌揭示了这一点:stackoverflow.com/questions/2250921/…
                • 如果混合可能需要更改
                【解决方案19】:

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

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

                【讨论】:

                  【解决方案20】:

                  在 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;
                  

                  【讨论】:

                    【解决方案21】:

                    如果有人还在读这篇文章,那么我用下面的方式访问 cshtml 文件。

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

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2016-08-07
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多