2014-09-26 39 views
3

問題是下面:通讀,看看你需要什麼幫忙解答...身份2.0定製的UserManager/RoleManager VS剃刀調用User.IsInRole( 「角色名」)

  • VS 2013
  • MVC 5與剃刀觀看
  • 小巧玲瓏DAL定製的UserManager和UserStore /用戶:IUSER < int>的

我建立我自己的UserManager,RoleManager,UserStore,Rolestore的,和所有基於CustomUser:IUSER < int>的和CustomRole:IRole < int>的

我可以修改密碼,恢復忘記的密碼,登錄,註銷......所有效果很好。

然而,在Razor視圖,當我嘗試使用:

User.IsInRole("Administrators"); 

我得到一個SQL異常,從其他模塊(這可能在IPrincipal的身份類???發生):

System.Data.SqlClient.SqlException occurred 
    _HResult=-2146232060 
    _message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 
    Source=.Net SqlClient Data Provider 
    ErrorCode=-2146232060 
    _doNotReconnect=false 
    Class=20 
    LineNumber=0 
    Number=-1 
    Server="" 
    State=0 
    StackTrace: 
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 
    InnerException: <null> 

但我可以叫

var user = AsyncHelpers.RunSync<CloudUser>(() => UserManager.FindByNameAsync(User.Identity.Name)); 
ViewBag.IsInAdminRole = AsyncHelpers.RunSync<bool>(() => UserManager.IsInRoleAsync(user.Id, "Administrators")); 

在我的控制器的服務器代碼....

問題:

  1. 什麼是User.IsInRole和的UserManager/UserStore和/或RoleManager之間

  2. 如何獲得User.IsInRole( 「管理員」)在剃刀的關係查看以「理解」它需要使用我的自定義身份驗證實施?

+0

當你把'@ User.GetType()。ToString()'放到視圖中時,你會看到什麼?即'IPrincipal'下的'User'是什麼類型? – trailmax 2014-09-27 22:46:17

+0

我知道你在想什麼。我自己通過派生自己的IPrincipal和WebView頁面來解決這個問題。我用這裏的解決方案來解決我的問題:http://stackoverflow.com/questions/18366566/how-would-i-mimic-user-isinrole – 2014-09-27 22:51:55

+0

啊,這很好!中途輸入一個答案,但你自己整理它! – trailmax 2014-09-27 22:53:49

回答

0

我懷疑你實現不提供ClaimsPrincipal當用戶已登錄。

@User應該ClaimsPrincipalIsInRolesee source)沒有達到進入數據庫,而是檢查類型的索賠「角色「確定校長的身份。如果您看到此例外情況,您的IPrincipal與「ClaimsPrincipal」不同。

我已閱讀您鏈接的答案,我不認爲這是使用Identity Framework的最佳解決方案。 The answer是身份識別前的內容,並會談到MembershipProvider。在處理MembershipProvider時,你必須做這些事情。現在,Identity爲您提供了更好,更清潔的自定義功能。

我建議不要實施CustomPrincipal並使用.Net框架提供的ClaimsPrincipal。當您從UserManager.CreateIdentityAsync返回IPrincipal時,只需在您的委託人中添加類型爲ClaimTypes.Role的索賠與角色名稱。

+1

我會給你答案,因爲我現在來自ClaimsPrincipal;公共類MyCustomPrincipal:ClaimsPrincipal,IMyCustomPrincipal ...但所有關於CustomPrincipal的其他代碼在提供的鏈接中被註釋掉了,並且我將它刪除了,因爲我不需要它。我甚至刪除了我已經在ClaimsPrincipal中處理過的IsInRole實現。感謝您對我的東西的審查。說,這裏不應該有'代碼審查'部分嗎?大聲笑 – 2014-09-29 14:13:27

+0

好!很高興它解決了,你不必使用黑客。關於代碼審查,有http://codereview.stackexchange.com/,但我從來沒有去過,所以不能說你是否會在那裏找到你的用途。 – trailmax 2014-09-29 14:33:51