2012-12-02 50 views
0

我想在asp.net中控制用戶身份驗證。從基頁控制身份驗證

假設; 有兩個類似StackOverflow.aspx和Default.aspx的網站。

我想用下面的代碼驗證角色:

public List<Roles> GetAuthenticatedRolesByModuleName(string moduleName) 
{ 
    //below I wrote psedeu code 
    var roles = "Select * From SiteRoles Where ModuleName = "Admin"; 
    //... 
} 
//This function returns a result set which includes roles authentication for `moduleName` parameter. 

我將與登錄到系統當前角色控制。

我想在asp.net的基本頁面中使用這個功能。

爲了做到這一點,我做了一個BasePage.cs,它繼承了System.Web.UI.Page。 我想寫GetAuthenticatedRolesByModuleName函數到BasePage.cs和當用戶輸入StackOverflow.aspx我想從BasePage.cs調用函數。

StackOverflow.aspx有pageload事件,我想我必須控制角色Init()

我使用Google搜索並找到一些來源,如:ASP.net "BasePage" class ideas 但我不明白。

我想從基本頁​​面函數(moduleName是堆棧溢出 - >GetAuthenticatedRolesByModuleName(stack-overflow))獲取角色並使用當前角色進行控制。 如果用戶未通過身份驗證,我會將其重定向到Default.aspx

Response.Redirect("Default.aspx"); 

我該怎麼辦?你能告訴我一個實現它的方法嗎?

+0

FormsAuthentication機制將是正確的選擇。 – vchyzhevskyi

+1

在stackoverflow.aspx.cs頁面中繼承BasePage.cs,並且您在BasePage中放置的每個公共/受保護方法都將在stackoverflow.aspx頁面中提供。 – Tariqulazam

回答

1

如果你犯了一個基本頁面進行全局檢查它使用OnpreInitOnInit會以某種方式那樣:

public abstract class BasePage : System.Web.UI.Page 
{ 
    protected override void OnPreInit(EventArgs e) 
    { 
     string cTheFile = HttpContext.Current.Request.Path; 

     // here select what part of that string you won to check out 
     if(!GetAuthenticatedRolesByModuleName(cTheFile)) 
     { 
      // some how avoid the crash if call the same page again 
      if(!cTheFile.EndsWith("Default.aspx")) 
      {  
       Response.Redirect("Default.aspx", true); 
       return ; 
      } 
     } 

     // continue with the rest of the page 
     base.OnPreInit(e); 
    } 
} 

,但你也可以用做相同的檢查和global.asaxApplication_AuthenticateRequest爲:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    // αυτό είναι το path... 
    string cTheFile = HttpContext.Current.Request.Path; 

    // here select what part of that string you won to check out 
    if(!GetAuthenticatedRolesByModuleName(cTheFile)) 
    { 
     // some how avoid the crash if call the same page again 
     if(!cTheFile.EndsWith("Default.aspx")) 
     {  
      Response.Redirect("Default.aspx", true); 
      Response.End(); 

      return ; 
     } 
    } 
}  

也許根據你的代碼需要添加一些細節,但這是一般的想法。