2011-09-26 13 views
11

如何知道是否请求是阿贾克斯在asp.net中的Application_Error()如何知道是否请求是阿贾克斯在asp.net中的Application_Error()

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

但现在我不能判断请求是哪种。我想从头文件中获得“X-Requested-With”,不幸的是,头文件的键不包含“X-Requested-With”键,为什么?

回答

20

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

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> 
+0

您确定Context.Request.Headers [“x-requested-with”]会返回“XMLHttpRequest”。我发送一个ajax请求,上面的代码返回null。 – dayulu

+1

@dayulu,绝对的,我告诉你的代码已经过测试。您的代码可能存在另一个问题:如果您有一些自定义全局筛选器拦截异常并执行重定向到错误页面,则x请求的标题将会丢失。 –

+0

你是对的!我得到null,因为请求重定向一次!非常感谢你! – dayulu

0

您可以使用此。

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

还可以包裹Context.Request(类型的HttpRequest的)在HttpRequestWrapper含有方法IsAjaxRequest。

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