如何知道如果请求是阿贾克斯asp.net中的Application_Error() [英] How to know if the request is ajax in asp.net in Application_Error()

查看:147
本文介绍了如何知道如果请求是阿贾克斯asp.net中的Application_Error()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to know if the request is ajax in asp.net in Application_Error()

我要处理的Application_Error(应用程序错误)。如果请求是阿贾克斯有些异常被抛出,然后写入日志文件中的错误并返回包含错误提示客户端JSON数据。
否则,如果该请求是同步以及一些异常被抛出,写入错误日志文件,然后重定向到一个错误页面。

I want to handle app error in Application_Error().If the request is ajax and some exception is thrown,then write the error in log file and return a json data that contains error tips for client . Else if the request is synchronism and some exception is thrown ,write the error in log file and then redirect to a error page.

但现在我不能判断哪一种的请求。我想从头部得到X-要求,用,可惜头项不包含X-要求,随着键,为什么?

but now i cant judge which kind the request is . I want to get "X-Requested-With" from header ,unfortunately keys of headers don't contain "X-Requested-With" key ,why?

推荐答案

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

Testing for the request header should work. For example:

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请求:

and then send some Ajax request:

<script type="text/javascript">
    $.get('@Url.Action("AjaxTest", "Home")', function (result) {
        if (result.error) {
            alert(result.error);
        }
    });
</script>

这篇关于如何知道如果请求是阿贾克斯asp.net中的Application_Error()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆