【问题标题】:How to get current user, and how to use User class in MVC5?如何获取当前用户,以及如何在 MVC5 中使用 User 类?
【发布时间】:2013-08-29 05:00:57
【问题描述】:
  • 如何在 MVC 5 中获取当前登录用户的 ID?我尝试了 StackOverflow 的建议,但它们似乎不适用于 MVC 5。
  • 另外,将内容分配给用户的 MVC 5 最佳实践是什么? (例如,User 应该有Items。我应该将用户的Id 存储在Item 中吗?我可以使用User 导航属性扩展User 类吗?

我正在使用 MVC 模板中的“个人用户帐户”。

试过这些:

'Membership.GetUser()' 为空。

【问题讨论】:

  • 添加了我尝试过的参考。最后一个在 MVC4 中可以,但在 MVC5 中不行。我还需要一些“使用用户”的最佳实践:)
  • 当你说你在使用 MVC 5 时,你用什么来做会员? OWin.Security?
  • MVC 模板中的“个人用户帐户”。
  • HttpContext.Current.User.Identity.Name 是当前登录用户的名称。
  • 如何获取Id?我想将当前用户分配给他创建的Item,但不是基于用户名(可能会改变)。顺便说一句,它不起作用`HttpContext.Current'System.Web.HttpContextBase'不包含'Current'的定义,并且找不到接受'System.Web.HttpContextBase'类型的第一个参数的扩展方法'Current'(您是否缺少 using 指令或程序集引用?)`。您确定您的解决方案适用于 MVC 5?

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity


【解决方案1】:

如果您在 ASP.NET MVC 控制器中编码,请使用

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

值得一提的是,User.Identity.IsAuthenticatedUser.Identity.Name 将在不添加上述 using 语句的情况下工作。但是没有它GetUserId() 就不会出现。

如果你在 Controller 以外的类中,请使用

HttpContext.Current.User.Identity.GetUserId();

在 MVC 5 的默认模板中,用户 ID 是存储为字符串的 GUID。

尚无最佳实践,但发现了一些有关扩展用户配置文件的有价值信息:

【讨论】:

  • 用户身份验证和授权已针对 ASP.NET MVC 5 进行了更改。现在它是基于声明的身份验证,具有可与 EF 或其他提供程序一起使用的接口和通用存储库(EF 实现是默认设置) .由于GetUserId 是存储在Ass_Start\IdentityConfig.cs 底部的扩展方法,因此无论您需要在何处使用它,如果在不同的命名空间中,您必须设置using Microsoft.AspNet.Identity 以使扩展可见。
  • survey.UserId = Guid.Parse(User.Identity.GetUserId());
  • 如果我添加使用参考用户仍然是红色下划线?为什么会这样?
  • @Zapnologica:尝试重建项目,可能 VS IntelliSense 有点慢。
  • 注意用户只能在控制器msdn.microsoft.com/en-us/library/… 中使用(@Zapnologica 你是在控制器之外使用它吗?试试 HttpContext.Current.User.Identity.GetUserId();)
【解决方案2】:

尝试类似:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

适用于 RTM。

【讨论】:

  • 它会导致不必要的数据库访问。
  • @Arash,应用程序如何在不联系数据库的情况下获取用户的对象?
  • @Arash 没关系,我明白你的意思。可以使用 User.Identity.GetUserId() 检索 ID;没有任何数据库之旅。
  • 记住 mvc5(成员资格 2):User.Identity.GetUserId() 与表 [AspNetUsers] 中的 id 不同。所以 Jakub Arnold 和 Rok 是正确的方法
  • 我对答案有点困惑。我的控制器上下文中似乎不存在 UserStore 类型。有什么想法吗?
【解决方案3】:

如果您希望 ApplicationUser 对象包含在一行代码中(如果您安装了最新的 ASP.NET Identity),请尝试:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

您需要以下 using 语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

【讨论】:

  • 找不到的对象
【解决方案4】:

获取 ID 非常简单,您已经解决了。

您的第二个问题涉及更多。

所以,现在这都是预发布的东西,但您面临的常见问题是您正在使用新属性(或者您的问题中的 Items 集合)扩展用户。

开箱即用,您将在 Models 文件夹下获得一个名为 IdentityModel 的文件(在撰写本文时)。在那里你有几节课; ApplicationUserApplicationDbContext。要添加您的 Items 集合,您需要修改 ApplicationUser 类,就像您在实体框架中使用的普通类一样。事实上,如果您快速浏览一下引擎盖,您会发现所有与身份相关的类(用户、角色等)现在都只是带有适当数据注释的 POCO,因此它们与 EF6 配合得很好。

接下来,您需要对 AccountController 构造函数进行一些更改,以便它知道使用您的 DbContext。

public AccountController()
{
    IdentityManager = new AuthenticationIdentityManager(
    new IdentityStore(new ApplicationDbContext()));
}

说实话,现在为您的登录用户获取整个用户对象有点深奥。

    var userWithItems = (ApplicationUser)await IdentityManager.Store.Users
    .FindAsync(User.Identity.GetUserId(), CancellationToken.None);

该行将完成工作,您将能够随意访问userWithItems.Items

HTH

【讨论】:

  • 我不认为有任何类似预发布文档的东西吗?
  • @Derek Tomes - 我没有遇到过。我认为我们必须等到 11 月 13 日才能获得真正的文档。老实说,这并不是很好,甚至有人要求在 uservoice 上提供更好的指导 - aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/…
  • 好的,但我如何获得AccountController 类型的实例?
【解决方案5】:

我感觉到你的痛苦,我正在尝试做同样的事情。就我而言,我只想清除用户。

我创建了一个基本控制器类,我的所有控制器都从该类继承。在其中我覆盖OnAuthentication 并设置filterContext.HttpContext.User to null

这是我迄今为止做到的最好的......

public abstract class ApplicationController : Controller   
{
    ...
    protected override void OnAuthentication(AuthenticationContext filterContext)
    {
        base.OnAuthentication(filterContext); 

        if ( ... )
        {
            // You may find that modifying the 
            // filterContext.HttpContext.User 
            // here works as desired. 
            // In my case I just set it to null
            filterContext.HttpContext.User = null;
        }
    }
    ...
}

【讨论】:

    【解决方案6】:
            string userName="";
            string userId = "";
            int uid = 0;
            if (HttpContext.Current != null && HttpContext.Current.User != null
                      && HttpContext.Current.User.Identity.Name != null)
            {
                userName = HttpContext.Current.User.Identity.Name;              
            }
            using (DevEntities context = new DevEntities())
            {
    
                  uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
                return uid;
            }
    
            return uid;
    

    【讨论】:

    • 请不要只发布代码,尤其是没有任何 cmets。如果你解释你的代码会更有帮助。
    【解决方案7】:

    如果其他人有这种情况: 我正在创建一个电子邮件验证来登录我的应用程序,所以我的用户还没有登录,但是我使用下面的内容来检查登录时输入的电子邮件,这是@firecape 解决方案的一种变体

     ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);
    

    您还需要以下物品:

    using Microsoft.AspNet.Identity;
    

    using Microsoft.AspNet.Identity.Owin;
    

    【讨论】:

      【解决方案8】:

      在 .Net MVC5 core 2.2 中,我使用 HttpContext.User.Identity.Name 。它对我有用。

      【讨论】:

        【解决方案9】:

        这就是我获得 AspNetUser Id 并将其显示在我的主页上的方式

        我将以下代码放在我的 HomeController Index() 方法中

        ViewBag.userId = User.Identity.GetUserId();
        

        在视图页面只需调用

        ViewBag.userId 
        

        运行该项目,您将能够看到您的 userId

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-20
          • 1970-01-01
          • 1970-01-01
          • 2015-02-18
          • 2019-07-10
          • 2020-10-05
          • 2021-11-12
          • 1970-01-01
          相关资源
          最近更新 更多