使用Identity 2.0,我已經修改爲使用整數作爲主鍵下面 http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity身份2.0與整數鍵:爲什麼User.IsInRole總是返回false?
除非從控制器,我稱之爲它的偉大工程:
User.IsUserInRole("admin");
它總是返回false。我檢查了底層表,數據沒有問題。
但是,如果我這樣做:
var t = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
bool ok = t.IsInRole(User.Identity.GetUserId<int>(), "admin");
然後正常工作。看來這個問題只在Controller.User
此外,屬性不工作,例如[Authorize(Roles = "admin")]
有人有過同樣的問題?
UPDATE:
它只不過與控制器有關,Thread.CurrentPrincipal
有同樣的問題:
Thread.CurrentPrincipal.IsInRole("admin");
更新2:
看來,問題出在AspNetUserRoles表。身份已添加一個新列,即我的擴展用戶表的外鍵。這對我來說似乎是多餘的,因爲有UserId列。問題是這個列的所有值都是NULL。我想如果我能夠理解如何重定向到UserId,一切都會正常工作。
[Authorize(Roles =「admin」)]和User.IsInRole檢查在登錄期間創建的cookie。您設置的身份驗證Cookie的方式不包括用戶的角色信息。 – DSR 2014-11-05 13:50:27
DSR,但是下面的代碼工作正常: var t = HttpContext.GetOwinContext()。GetUserManager(); bool ok = t.IsInRole(User.Identity.GetUserId (),「admin」); –
2014-11-05 15:54:05
是的,沒錯,因爲您直接使用該代碼訪問數據庫。 [Authorize(Roles =「admin」)]和User.IsInRole不訪問數據庫,而是從認證cookie獲取信息。發佈您的owin啓動代碼,在其中設置您的身份驗證Cookie。按照這些視頻教程http://stackoverflow.com/questions/25857806/extending-identityuserrole-in-identity-2-0/25857923#25857923 – DSR 2014-11-05 16:15:53