2017-07-07 49 views
0

我知道有很多關於這個問題的主題,但我已經嘗試了幾種解決方案,無法使其工作。ASP.net MVC - 獲取當前記錄的用戶角色

所以,我想在我的視圖中驗證當前記錄的用戶角色。正如有關此內容的StackOverflow主題的重要組成部分提到,我只需要做:

@User.IsInRole("Admin") 

很不幸,這始終返回false甚至與「角色」欄,在AspNetUsers表,當前登錄的用戶是填充「管理員」。

我也嘗試了下面的方法,但它說「UserManager在當前上下文中不存在」。

<p>@UserManager.GetRoles(userId)</p> 

我的一個嫌疑人是我在註冊時沒有正確地爲用戶設置角色。我的AspNetRoles表正確填充,但AspNetUserRoles表爲空。

如何解決此問題以查找我的應用程序出現了什麼問題,以便我可以使用@ User.IsInRole(...)指令?

在此先感謝您的幫助。

+0

你說「甚至在該用戶的AspNetUsers表中的'角色'列是'Admin'」,但是然後說「AspNetUserRoles表是空的」。如果有一個連接/交叉引用表,那麼AspNetUsers表上就不會有一個Role列。 – krillgar

+0

@krillgar感謝您的回覆。我不確定我是否完全理解你的觀點,但你是否說我的AspNetUsersRoles表不應該是空的? – myusername21

+1

是的。由於用戶可以有很多角色,並且許多用戶將處於同一個角色中,所以AspNetUsers表上不應該有角色列。因爲你的AspNetUserRoles表是空的,那告訴我沒有用戶實際上分配了角色。 – krillgar

回答

0

您是否嘗試過在視圖頁面的頂部添加如下:

@using Microsoft.AspNet.Identity 

或者:

@if(Roles.IsUserInRole(User.Identity.GetUserName(), "Admin")) 
0

我想你不寫,或者你寫的,但在錯誤的道路這下面的代碼on global.asax:

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) 
    { 

     if (FormsAuthentication.CookiesSupported == true) 
     { 
      if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) 
      { 
       try 
       { 
        //let us take out the username now     
        string Email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; 
        string roles = string.Empty; 

        using (DatabaseContext entities = new DatabaseContext()) 
        { 
         var user = entities.TblUsers.Where(u => u.Email == Email).FirstOrDefault().IDRole; 

         //here 
         roles = entities.TblRoles.Where(x => x.IDRole == user).FirstOrDefault().RoleName; 

        } 
        //let us extract the roles from our own custom cookie 

        // and here 
        //Let us set the Pricipal with our user specific details 
        e.User = new System.Security.Principal.GenericPrincipal(
         new System.Security.Principal.GenericIdentity(Email, "Forms"), roles.Split(';')); 

       } 
       catch 
       { 

        //somehting went wrong 
       } 
      } 
     } 
    } 
相關問題