2012-01-31 50 views
0

我想讓開發人員更容易, 由於有多種認證選項,並非所有頁面都需要認證或完全認證。如何在Razor中使用PageLoad?

在的WebForms,我可以有一個通用的網頁, 現在每個頁面繼承GenericPage,只需要implemenet AuthorizationType(見下面的代碼)

我可以做任何事情similiar剃刀? 或者,也許我應該財產以後完全不同......

這裏是的WebForms代碼:

public class GenericPage : Page 
{ 
    public enum AuthorizationType 
    { 
     Users = 1, 
     AuthUsers = 2, 
     Admins = 4 
    } 

    public virtual bool IsAuth() 
    { 
     return Authenticator.IsAuth(); 
    } 

    public virtual bool IsAdmin() 
    { 
     AuthUser authUser = Authenticator.GetAuthenticatedUser(); 
     return (authUser != null && authUser.IsAdmin) 
    } 

    protected abstract AuthorizationType Authorization 
    { 
     get; 
    } 

    protected virtual string OnAuthorizationFailedUrl 
    { 
     get 
     { 
      return HomePageUrl; 
     } 
    } 

    protected void CheckAuthentication() 
    { 
     if (!IsUserAuthroized()) 
      Response.Redirect(OnAuthorizationFailedUrl); 
    } 

    protected bool IsUserAuthroized() 
    { 
     AuthorizationType authorization = Authorization; 
     return (Authorization.Contains(AuthorizationType.Users) || 
       (Authorization.Contains(AuthorizationType.AuthUsers) && IsAuth()) || 
       (Authorization.Contains(AuthorizationType.Admins) && IsAdmin())); 
    } 

    override OnPageLoad() 
    { 
     CheckAuthentication(); 
    } 
} 

在此先感謝。

回答

3

在你的情況下,可以實現3種類型的角色。在對用戶進行身份驗證時,請正確分配角色。

然後在你的控制器,或控制器操作的方法,就可以把授權屬性

[授權(角色= 「用戶」)

或多個角色

[授權(角色=「用戶,管理員「)]

如果要全局過濾,可以創建BaseController並將Authorize屬性授予控制器。然後你所有的控制器都需要實現BaseController。

這是我的博客文章,介紹如何使用自定義標識實現身份驗證。

https://kevww.wordpress.com/2011/11/18/implement-formsauthentication-with-custom-identity-in-asp-net-mvc/

希望這可以幫助你

相關問題