2011-06-13 59 views
1

This article解釋了PreRequestHandlerExecute事件不會爲任何原因觸發PageMethod調用。但是,我試圖使用該事件來填充具有用戶權限的Principal對象,以便可以在任何Web請求(PageMethod調用或不調用)中檢查它們。我在會話中緩存權限,因此我需要一個事件,該事件在每次調用PageMethod時觸發,並且需要訪問會話。通過這種方式,我可以使用會話中緩存的安全權限填充Principal對象,User.IsInRole()調用將按預期工作。我可以使用什麼活動?對於PageMethods,Application_PreRequestHandlerExecute事件不會觸發。我可以用什麼來代替?

+0

這些答案中的任何一個能解決您的問題嗎? – 2011-07-23 13:35:21

回答

1

您可以使用Application_OnPostAuthenticateRequest如下圖所示(假設您正在使用窗體身份驗證否則,請更換您的身份驗證機制的代碼。):

public void Application_OnPostAuthenticateRequest(object sender, EventArgs e) 
{ 

    IPrincipal usr = HttpContext.Current.User; 

    if (usr.Identity.IsAuthenticated && usr.Identity.AuthenticationType == "Forms") 
    { 
     var fIdent = (FormsIdentity)usr.Identity; 
     var ci = new CustomIdentity(fIdent.Ticket); 
     var p = new CustomPrincipal(ci); 

     HttpContext.Current.User = p; 
     Thread.CurrentPrincipal = p; 
    } 

} 
+0

這不適用於我 - 此時我沒有會話。 – 2011-06-13 17:37:29

+0

你可以試試HttpContext.Session [「key」]嗎? – Akhil 2011-06-13 17:42:07

+0

HttpContext.Current.Session爲null。 – 2011-06-13 17:43:55

2

你應該實現,將與每一個上升到服務器的請求上運行的授權模塊。這樣,您就能夠授權您所出現的服務器的任何請求委託人(頁面請求,方法等)

public class AuthorizationModule : IHttpModule, IRequiresSessionState 
{ 
    //not going to implement it fully, might not compile 

    public void Init(HttpApplication context) 
    { 
     //you'll prolly want to hook up to the acquire request state event, but read up to make sure this is the one you want on the msdn 
     context.AcquireRequestState += AuthorizeRequest; 
    } 

    public void AuthorizeRequest(HttpContextBase httpContext) 
    { 
     // do you work in here 

     // you can redirect them wherever if they don't have permssion, log them out, etc 
    } 
    } 
} 

你裝箱模塊後,你需要把它掛在web.config中。你的類型應該包含命名空間,如果它有的話。

<httpModules> 
    <add name="AuthorizationModule" type="AuthorizationModule"/> 
</httpModules> 

我希望這會有所幫助。

1

頁面方法是靜態的,繞過正常的頁面生命週期,其對象及其事件。您可以做的最好的方法是將認證信息作爲參數傳遞給Page Method本身。

相關問題