如何知道请求是否是Application_Error()中的asp.net中的ajax
我想在Application_Error().If中处理应用程序错误,请求是ajax并抛出一些异常,然后将错误写入日志文件并返回包含客户端错误提示的json数据。否则,如果请求是同步的,并且抛出了一些异常,则在日志文件中写入错误,然后重定向到错误页面。
但现在我不能判断是哪种类型的请求。我想从头部获取"X-Requested-With“,不幸的是头部的键没有包含"X-Requested-With”键,为什么?
发布于 2011-09-26 14:59:27
对请求头的测试应该是有效的。例如:
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>发布于 2015-09-30 21:45:57
您还可以将Context.Request (类型为HttpRequest)包装在包含方法IsAjaxRequest的HttpRequestWrapper中。
bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();发布于 2011-09-26 14:46:15
可以在客户端ajax调用中添加自定义头。参考http://forums.asp.net/t/1229399.aspx/1
尝试在服务器中查找此标头值。
https://stackoverflow.com/questions/7551424
复制相似问题