测试请求标头应该工作。例如:
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>
您确定Context.Request.Headers [“x-requested-with”]会返回“XMLHttpRequest”。我发送一个ajax请求,上面的代码返回null。 – dayulu
@dayulu,绝对的,我告诉你的代码已经过测试。您的代码可能存在另一个问题:如果您有一些自定义全局筛选器拦截异常并执行重定向到错误页面,则x请求的标题将会丢失。 –
你是对的!我得到null,因为请求重定向一次!非常感谢你! – dayulu