13

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

我想在 Application_Error() 中处理应用程序错误。如果请求是 ajax 并且引发了一些异常,则将错误写入日志文件并返回包含客户端错误提示的 json 数据。否则,如果请求是同步的并且抛出了一些异常,则将错误写入日志文件,然后重定向到错误页面。

但现在我无法判断请求是哪种类型。我想从标题中获取“X-Requested-With”,不幸的是标题的键不包含“X-Requested-With”键,为什么?

4

4 回答 4

23

测试请求标头应该可以工作。例如:

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>
于 2011-09-26T06:59:26.823 回答
7

You can also wrap the Context.Request (of the type HttpRequest) in a HttpRequestWrapper which contains a method IsAjaxRequest.

bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
于 2015-09-30T13:45:56.907 回答
0

可以在客户端 ajax 调用中添加自定义标头。参考http://forums.asp.net/t/1229399.aspx/1

尝试在服务器中查找此标头值。

于 2011-09-26T06:46:14.950 回答
0

你可以用这个。

    private static bool IsAjaxRequest()
    {
        return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }
于 2015-08-25T04:40:25.140 回答