【问题标题】:How can I get all users with ASP.NET Identity based on a property?如何根据属性获取所有具有 ASP.NET 身份的用户?
【发布时间】:2014-04-29 06:39:58
【问题描述】:

我尝试了一些非常简单的东西,但无论出于何种原因它都不起作用,因此我在这里看看是否有什么能给我带来启示,我在其他地方找不到示例或解决方案(Bing/google)

问题很简单,我使用的是稍微修改过的 ApplicationUser 类:

 public class ApplicationUser : IdentityUser
{
    public virtual Guid BusinessId { get; set; }
}

使用以下助手(扩展方法):

public static Guid GetBusinessId(this IIdentity user)
    {
         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
         var currentUser = manager.FindById(user.GetUserId());

        return currentUser.BusinessId;
    }

最后是“导致”问题的方法:

public IQueryable<ApplicationUser> Get()
    {
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        Guid businessId = this.User.Identity.GetBusinessId();
        var users = userManager.Users.Where(u => u.BusinessId == businessId);

        return users;
    }

这里发生的情况是,当我查询用户时,我什么也得不到,但它至少应该得到当前登录的用户,因为他有正确的 businessId。

如果我在用户查询上设置断点并在即时窗口上尝试“ToList()”或“ToList()[0]”之类的操作,我会得到以下信息:

?users.ToList()
Count = 1
[0]: Could not evaluate expression
?users.ToList()[0]
An internal error has occurred while evaluating method System.Collections.Generic.List`1[T].get_Item().

任何想法为什么,或者是否有这样做的“正确”方式?

谢谢

【问题讨论】:

  • 什么是内部错误(内部异常)?
  • 我也不例外,你在上面看到的是我完全复制和粘贴的直接窗口的结果。
  • 您是否检查过 businessId 的值是否有效? (例如不是 Guid.Empty)
  • 是的,我做到了,它确实有一个值在 SQL 管理器上执行以确认它应该返回一条记录

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


【解决方案1】:

看看这里How to obtain a list of Users from ASP.NET Identity? qouted from answer

我发现我没有将派生的 ApplicationUser 对象用于任何事情,所以我继续更改它的所有用途 普通老用户。然后我只是更改了 ApplicationDbContext 定义 对于以下内容:

public class ApplicationDbContext : IdentityDbContext<
    User, UserClaim, UserSecret, UserLogin,
    Role, UserRole, Token, UserManagement>
{
}

现在我可以访问用户列表了:

 UsersContext = new ApplicationDbContext();
 ...
 UsersContext.Users.ToList();

但是,我认为这会在未来再次出现并困扰我(我会 可能需要向用户添加更多字段)所以我可能不得不使用 与此问题相同的方法:

获取 ASP.NET MVC5 身份系统中的所有角色名称

编辑:因为我需要添加一个新属性,所以我不得不恢复我的 变化。所以我继续进行逐行比较 ASP.NET Identity Sample Project,发现生成的 项目有以下行:

IdentityManager = new AuthenticationIdentityManager(new IdentityStore());

虽然示例应用程序已将数据库上下文包含在 构造函数。所以我将它添加到我的构造函数中,重新创建了数据库 问题就解决了。

【讨论】:

  • 我找不到他所说的 IdentityManager 和 AuthenticationIdentityManager,第一个示例不起作用,因为我对 ApplicationUser 进行了修改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多