2014-01-23 50 views
3

......我們只在Microsoft.AspNet.Identity內部。 (我們甚至沒有在Microsoft.AspNet.Identity.EntityFramework上查看基礎實現。)ASP.net身份 - UserManager <TUser>如何訪問角色?

UserManager類僅在構造函數中採用IUserStore<TUser>。它沒有IUserRoleStore<TUserRole>,我想這需要被訪問以確定是否UserManager.IsInRoleAsync(string, string)

我在想UserStore的實現也會有一個IsInRoleAsync(string, string)的功能(那麼它們都會有意義),但事實並非如此。

另一個奇怪的事情 - 如果UserManager能夠執行密碼設置和重置,如果它知道它的實現內容是我們正在處理IUser - 只有string Idstring UserName作爲屬性?

回答

5

好吧,經過多次挖掘和發現幸運的 - 事實證明,Microsoft.AspNet.Identity.Core帶有一些其他的接口,特別是IUserRoleStore<TUser>IUserPasswordStore<TUser>這兩個「繼承」(實施)IUserStore <TUSER>

因此,如果我們想角色的管理能力,我們實現IUserRoleStore<TUser>

class MyUser : IUser 
{ 
     // Additional properties and functions not shown for brevity. 
} 

class MyUserStore : IUserRoleStore<MyUser> 
{ 
    public bool IsInRole(string username, string role) 
    { 
     // Implementation not show for brevity. 
    } 


    /* We would then implement the rest of the required functions. 

     We would have a data context here that has access to users, 
     user-roles, and roles. 
    */ 
} 

現在我們可以通過MyUserStoreUserManager<TUser>,因爲MyUserStoreIUserRoleStore<TUser>,這是一個IUserStore<TUser>

UserManager<MyUser> UM = new UserManager<MyUser>(new MyUserStore()); 

我那麼懷疑UserManager<TUser>的源代碼使用反射來確定商店是否在構造中傳入它或實現IUserStore<TUserStore>的「子接口」之一,以便能夠執行角色檢查(如果它實現IUserRoleStore<TUser>)或密碼設置/重置(如果它實現IUserPasswordStore<TUser>)。

我希望你覺得這很有用,因爲大多數文檔(MVC教程等)都沒有告訴我們這個細節。他們告訴我們使用Microsoft.AspNet.Identity.EntityFramework的UserStore<TUser>實現 - 我們所要做的就是傳遞一個自定義的User對象(實現IUser),我們很好。

+0

這是如何工作的激動人心。你可以在https://github.com/aspnet/Identity找到源代碼。他們正在做'var cast =存儲爲IUserRoleStore ;'以檢查您的傳遞的商店是否實現了'IUserRoleStore '。 – qbik

相關問題