Asp.net-Mvc
User.IsInRole 返回 false
我在 mvc 5 網站中使用 Identity 2 進行身份驗證。在我看來,我想檢查使用者的角色:
@if(User.IsInRole("Customers")) { @*do something*@ }但這總是返回 false,我已經
<roleManager enabled="true" />在 web 配置中設置了。請提供任何幫助。
我剛剛讓它與我的設置一起使用,該設置也使用身份框架。
我使用以下程式碼將使用者添加到角色:
this.RoleManager.CreateAsync(new Role() {Name = "Customers"}); this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");然後在那之後的任何時候,當我執行它時
User.IsInRole("Customers");它返回錯誤,直到我重新登錄它們。將使用者添加到角色後,您需要重新登錄使用者。角色資訊儲存在 cookie 中。
我執行以下命令再次記錄使用者:
var user = await this.UserManager.FindByNameAsync("bob"); var identity = await this.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); this.AuthManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);從這一點開始,
User.IsInRole("Customers")為我工作並返回true。除非您可以在應用程序中驗證它是否知道您要將它們添加到的角色,否則這將不起作用。您可以通過以下方式使用 RoleManager 驗證角色“客戶”的存在:
var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);