2017-04-24 40 views
0

我想從User對象訪問我的視圖中的一些自定義屬性。我正在實現身份驗證的自定義屬性,我正在更改我的global.asax中的HttpContext.Current.User如何訪問視圖中的HttpContext.Current.User自定義屬性

這是User

public class User : IPrincipal 
{ 
    ... 
    public bool IsAdministrator => IsInRole(RolesConstants.GlobalAdministrator); 
    ... 
} 

這裏是我設置在我Global.asax

protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e) 
    { 
     ... 

     var winUser = new User 
     { 
      EMail = user.Person.Email, 
      FirstName = user.Person.FirstName, 
      LastName = user.Person.LastName, 
      Identity = wi, 
      NetworkAccountName = user.UserName, 
      UserId = user.UserName, 
      Roles = userRoles, 
     }; 

     HttpContext.Current.User = winUser; 
    } 

例如,我怎麼能這樣做?

<button type="button" visible="@User.IsAdministrator" id="btn"></button> 

由於User對象已經接近我不想在Model傳遞或使用字符串中的觀點,如@User.IsInRole("Admin")

編輯:我應該做一個自定義類型從IPrinciple派生並探討這樣的類型?

... 
     IIdentity Identity { get; } 
     bool IsInRole(string role); 
     bool IsAdministrator; 
... 
+0

您確定@User在視圖中可用嗎? –

+0

你可以創建一個自定義的'RazorViewBase'類並從它派生你的視圖。自定義類可以爲用戶提供自己的視圖實現。 –

+0

@Kevin,是的,它是 –

回答

2

您需要的User物業投放到您的自定義類:

@{ 
    var user = User as MyNamespace.User; // MyNamespace is the namespace of your User class 
} 

<button type="button" visible="@user.IsAdministrator" id="btn"></button> 

[編輯]

使用的擴展方法的另一種快速和骯髒的解決方案:

public static class ViewUserExtensions { 

    public static User ToCustom(this IPrincipal principal) 
    { 
     return principal as User; 
    } 
} 

<button type="button" visible="@User.ToCustom().IsAdministrator" id="btn"></button> 
+0

擴展方法只能在服務器端訪問。有什麼缺失來實現它?我寧願讓這個視圖比視圖變量 –

+0

當然,因爲視圖是在服務器端渲染的。請記住在視圖中添加正確的using語句,以便可以使用擴展方法'@using MyNamespace',其中'MyNamespace'是包含'ViewUserExtensions'類的命名空間。 –

+0

Doh,非常感謝! –