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

day*_*ulu 12 c# asp.net asp.net-mvc web-applications application-error

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

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

但现在我无法判断请求是哪种.我想从标题中获取"X-Requested-With",遗憾的是标题的键不包含"X-Requested-With"键,为什么?

Dar*_*rov 21

测试请求标头应该有效.例如:

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

    public ActionResult AjaxTest()
    {
        throw new Exception();
    }
}
Run Code Online (Sandbox Code Playgroud)

并在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" }
            )
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

然后发送一些Ajax请求:

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


小智 6

您还可以将 Context.Request(属于 HttpRequest 类型)包装在包含方法 IsAjaxRequest 的 HttpRequestWrapper 中。

bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
Run Code Online (Sandbox Code Playgroud)