簡體   English   中英

如何在Application_Error()中知道asp.net中的請求是ajax

[英]How to know if the request is ajax in asp.net in Application_Error()

如何在Application_Error()中知道asp.net中的請求是ajax

我想在Application_Error()中處理應用程序錯誤。如果請求是ajax並且拋出了一些異常,則在日志文件中寫入錯誤並返回包含客戶端錯誤提示的json數據。 否則,如果請求是同步並且拋出了一些異常,請在日志文件中寫入錯誤,然后重定向到錯誤頁面。

但現在我無法判斷請求是哪種。 我想從標題中獲取“X-Requested-With”,遺憾的是標題的鍵不包含“X-Requested-With”鍵,為什么?

測試請求標頭應該有效。 例如:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult AjaxTest()
    {
        throw new Exception();
    }
}

並在Application_Error

protected void Application_Error()
{
    bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
    Context.ClearError();
    if (isAjaxCall)
    {
        Context.Response.ContentType = "application/json";
        Context.Response.StatusCode = 200;
        Context.Response.Write(
            new JavaScriptSerializer().Serialize(
                new { error = "some nasty error occured" }
            )
        );
    }

}

然后發送一些Ajax請求:

<script type="text/javascript">
    $.get('@Url.Action("AjaxTest", "Home")', function (result) {
        if (result.error) {
            alert(result.error);
        }
    });
</script>

您還可以在包含方法IsAjaxRequest的HttpRequestWrapper中包裝Context.Request(類型為HttpRequest)。

bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();

你可以用它。

    private static bool IsAjaxRequest()
    {
        return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }

可以在客戶端ajax調用中添加自定義標頭。 請參閱http://forums.asp.net/t/1229399.aspx/1

嘗試在服務器中查找此標頭值。

暫無
暫無

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

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