2016-08-22 56 views
0

爲什麼cshtml顯示不在我角色中的用戶的鏈接?
爲什麼cshtml顯示不在我角色中的用戶的鏈接?

要清楚非管理員用戶不應該看到重置密碼和創建用戶鏈接。就我而言,他們正在看到鏈接。

在我layout.cshtml我有以下代碼:

 @if (HttpContext.Current.User.Identity.IsAuthenticated) 
     { 
      @Html.ActionLink("My Wonderful App", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) 
      <span class="navbar-right"> 
       if (HttpContext.Current.User.IsInRole("Administrators")) 
       { 
        @Html.ActionLink("Reset Password", "ResetPassword", "Auth", null, new { @class = "navbar-brand" }) 
        @Html.ActionLink("Create User", "CreateAccount", "Auth", null, new { @class = "navbar-brand" }) 
       } 
       @Html.ActionLink("Logoff", "Logoff", "Auth", null, new { @class = "navbar-brand" }) 
      </span> 
     } 

在我的控制器時,在我的用戶登錄有:

// For clarity assume: 
// userName = "[email protected]" 
// IsAdmin = false 

var identity = new ClaimsIdentity(new[] { 
           new Claim(ClaimTypes.Name, userName), 
           new Claim(ClaimTypes.Email, userName)         
          }, "ApplicationCookie"); 

         if (IsAdmin) 
         { 
          identity.AddClaim(new Claim(ClaimTypes.Role, "Administrators")); 
         } 
         else 
         { 
          identity.AddClaim(new Claim(ClaimTypes.Role, "User")); 
         } 

         var ctx = Request.GetOwinContext(); 
         var authManager = ctx.Authentication; 

         authManager.SignIn(identity); 

該控制器由當拒絕訪問正常工作用戶點擊鏈接。

[Authorize(Roles="Administrators")] 

回答

0

原來是一個剃刀語法問題。

@if (HttpContext.Current.User.Identity.IsAuthenticated) 
    { 
     @Html.ActionLink("My Wonderful App", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) 
     <span class="navbar-right"> 
      if (HttpContext.Current.User.IsInRole("Administrators")) 
      { 
       @Html.ActionLink("Reset Password", "ResetPassword", "Auth", null, new { @class = "navbar-brand" }) 
       @Html.ActionLink("Create User", "CreateAccount", "Auth", null, new { @class = "navbar-brand" }) 
      } 
      @Html.ActionLink("Logoff", "Logoff", "Auth", null, new { @class = "navbar-brand" }) 
     </span> 
    } 

本來應該是:

@if (HttpContext.Current.User.Identity.IsAuthenticated) 
{ 
    @Html.ActionLink("My Wonderful App", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) 
    <span class="navbar-right"> 
     @if (HttpContext.Current.User.IsInRole("Administrators")) 
     { 
      @Html.ActionLink("Reset Password", "ResetPassword", "Auth", null, new { @class = "navbar-brand" }) 
      @Html.ActionLink("Create User", "CreateAccount", "Auth", null, new { @class = "navbar-brand" }) 
     } 
     @Html.ActionLink("Logoff", "Logoff", "Auth", null, new { @class = "navbar-brand" }) 
    </span> 
} 
相關問題