Asp.net

如何從 ASP.NET Identity 獲取使用者列表?

  • September 12, 2013

編輯:這個問題已經過時了

在我提出這個問題時,身份框架是一個移動的目標。作者改變了很多東西,他們解耦了其他一些東西,讓一切變得更容易。

查看github上的Asp.NET Identity Sample 項目。


我正在創建一個需要使用者管理的小型應用程序。不允許註冊,而是有一個超級使用者將創建和修改登錄資訊。

我正在使用新的ASP.NET Identity成員資格系統,果然,創建使用者和添加角色既簡單又直覺。

現在,我的問題是:如何使用生成的 AccountController 類使用的 AuthenticationIdentityManager 類獲取使用者列表?我找不到從控制器訪問使用者列表的方法。

(順便說一句,新名稱“身份”對某些人來說可能聽起來很棒,但搜尋起來很痛苦。)

編輯:如果我嘗試這樣做

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

我得到一個例外Invalid column name 'Discriminator'。ApplicationDbContext 的定義由新應用程序嚮導自動生成:

using Microsoft.AspNet.Identity.EntityFramework;

namespace Cobranzas.Models
{
   public class ApplicationUser : User
   {

   }
   public class ApplicationDbContext : IdentityDbContextWithCustomUser<ApplicationUser>
   {

   }
}

所以我的猜測是該Discriminator列用於區分ApplicationUser. User但是,它在我的數據庫中不存在(由應用程序自動創建。)

我發現我沒有將派生ApplicationUser對像用於任何事情,所以我繼續將它的所有用途更改為普通的 old User。然後我只是更改ApplicationDbContext了以下內容的定義:

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

現在我可以訪問使用者列表:

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

但是,我認為這將來會回來困擾我(我可能需要向 中添加更多欄位User),所以我可能不得不使用與這個問題相同的方法:

獲取 ASP.NET MVC5 身份系統中的所有角色名稱

編輯:由於我需要添加一個新屬性,我不得不恢復我的更改。於是我繼續與 ASP.NET Identity Sample Project 進行了逐行比較,發現生成的項目有以下行:

IdentityManager = new AuthenticationIdentityManager(new IdentityStore());

而範例應用程序在建構子中包含了數據庫上下文。所以我在建構子中添加了它,重新創建了數據庫,問題就消失了。

IdentityManager = new AuthenticationIdentityManager(new IdentityStore(new ApplicationDbContext()));

引用自:https://stackoverflow.com/questions/18773838