Detecting Ajax requests on the server

Posted on April 6, 2010 by Frederik Vig in ASP.NET, JavaScript

If you use jQuery or ASP.NET AJAX you can easily detect Ajax requests on the server by simply checking for the HTTP_X_REQUESTED_WITH HTTP Header. Both libraries automatically add this to the HTTP Header when they send a request.

Here’s a little code snippet that returns true for Ajax requests.

public static bool IsAjaxRequest()
{
    return HttpContext.Current.Request.Headers["X-Requested-With"] != null && HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

The cool thing about this is that you can use this in a base page or a HTTP Module, and customize the returned data. You could for instance return JSON or XML.

using System;
using System.Web.UI;
 
namespace MyWebApplication
{
    public class BasePage : Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
 
            if (Helper.IsAjaxRequest())
            {
                Response.Headers.Clear();
                Response.ContentType = "application/json";
                Response.Write(json output);
                Response.End();
            }
        }
    }
}

Related Posts: