簡體   English   中英

如何在ASP.NET Application_Error事件中確定當前請求是否是異步回發

[英]How to determine if current request is an asynchronous postback, in ASP.NET Application_Error event

是否可以從Application_Error事件中確定當前請求是否是異步回發(部分頁面更新)?

使用異步回發時,處理應用程序錯誤的最佳方法是什么?

在Application_Error中,我們重定向到不同的錯誤頁面,但在異步回發期間拋出錯誤時,該方法無法正常工作。 我們注意到,即使AllowCustomErrorsRedirect = false,我們也有一個OnAsyncPostBackError處理程序來設置AsyncPostBackErrorMessage。 在異步回發期間,我們的AsyncPostBackErrorMessage被覆蓋,客戶端會收到通用網頁錯誤。

Application_Error方法中,您不再可以直接訪問頁面上的<asp:ScriptManager>控件。 因此處理其AsyncPostBackError事件為時已晚。

如果要阻止重定向,則應檢查請求以確定它是否實際上是異步請求。 <asp:UpdatePanel>使用以下HTTP標頭返回帖子:

X-MicrosoftAjax:Delta=true

(另請參閱: ScriptManager在您的Web應用程序中啟用AJAX

檢查此標頭將如下所示:

HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
if(header != null && header == "Delta=true") 
{
  // This is an async postback
}
else
{
  // Regular request
}

至於處理異常的適當方式是一個不同的問題imho。

我有類似的情況。 對我Server.ClearError()是在我的事件處理程序中為ScriptManager的AsyncPostBackError調用Server.ClearError() 這可以防止調用Global.asax Application_Error函數。

在Application_Error中,您實際上可以訪問ScriptManager以確定當前請求是否是異步回發。 全局對象HttpContext.Current.Handler實際上指向正在服務的頁面,其中包含ScriptManager對象,該對象將告訴您當前請求是否是異步的。

以下語句簡要說明了如何訪問ScriptManager對象並獲取以下信息:

ScriptManager.GetCurrent(CType(HttpContext.Current.Handler, Page)).IsInAsyncPostBack

當然,如果當前請求不是針對頁面,或者當前頁面上沒有ScriptManager,那么該語句將失敗,因此這里有一對更強大的函數可以在Global.asax中使用來做出決定:

Private Function GetCurrentScriptManager() As ScriptManager
    'Attempts to get the script manager for the current page, if there is one

    'Return nothing if the current request is not for a page
    If Not TypeOf HttpContext.Current.Handler Is Page Then Return Nothing

    'Get page
    Dim p As Page = CType(HttpContext.Current.Handler, Page)

    'Get ScriptManager (if there is one)
    Dim sm As ScriptManager = ScriptManager.GetCurrent(p)

    'Return the script manager (or nothing)
    Return sm
End Function

Private Function IsInAsyncPostback() As Boolean
    'Returns true if we are currently in an async postback to a page

    'Get current ScriptManager, if there is one
    Dim sm As ScriptManager = GetCurrentScriptManager()

    'Return false if no ScriptManager
    If sm Is Nothing Then Return False

    'Otherwise, use value from ScriptManager
    Return sm.IsInAsyncPostBack
End Function

只需從Application_Error中調用IsInAsyncPostback()以獲取指示當前狀態的布爾值。

您在客戶端遇到通用ASP.NET錯誤,因為嘗試傳輸/重定向異步請求將產生更多錯誤,從而替換並因此混淆原始錯誤。 在這種情況下,您可以使用上面的代碼來防止傳輸或重定向。

另請注意我做的另一個發現:即使您可以使用此方法訪問ScriptManager對象,由於某種原因從Application_Error中設置其AsyncPostBackErrorMessage屬性也不起作用。 新值不會傳遞給客戶端。 因此,您仍然需要在頁面類中處理ScriptManager的OnAsyncPostBackError事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM