asp.net中Application_Error()如何知道请求是否是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();
}
}
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" }
)
);
}
}
然后发送一些 Ajax 请求:
<script type="text/javascript">
$.get('@Url.Action("AjaxTest", "Home")', function (result) {
if (result.error) {
alert(result.error);
}
});
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)