How to know if the request is ajax in asp.net in Application_Error()
I want to handle app error in Application_Error().If the request is ajax and some exception is t
Testing for the request header should work. For example:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AjaxTest()
{
throw new Exception();
}
}
and in 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" }
)
);
}
}
and then send some Ajax request: