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

4

14

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 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.

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?

Babs answered 26/9, 2011 at 6:40 Comment(0)
A
23

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:

<script type="text/javascript">
    $.get('@Url.Action("AjaxTest", "Home")', function (result) {
        if (result.error) {
            alert(result.error);
        }
    });
</script>
Aliform answered 26/9, 2011 at 6:59 Comment(4)
Are you sure that Context.Request.Headers["x-requested-with"] would return "XMLHttpRequest". I send a ajax request above code return null.Babs
@dayulu, absolutely, the code I have shown you was tested. There could be another issue with your code: if you have some custom global filter which intercepts exceptions and performs a redirect to an error page then the x-requested-with header will be lost.Aliform
You are right! I get null ,because the request redirect one time! Thank you very much!Babs
This doesn't work in global.asax. Use __CALLBACKID instead. Hope this helps.Decennium
C
9

You can also wrap the Context.Request (of the type HttpRequest) in a HttpRequestWrapper which contains a method IsAjaxRequest.

bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
Cimino answered 30/9, 2015 at 13:45 Comment(0)
D
0

it is possible to add custom headers in the client side ajax call. Refer http://forums.asp.net/t/1229399.aspx/1

Try looking for this header value in the server.

Dotson answered 26/9, 2011 at 6:46 Comment(0)
A
0

You could use this.

    private static bool IsAjaxRequest()
    {
        return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }
Any answered 25/8, 2015 at 4:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.