Freigeben über


AJAX Extension Methods

Although the ScriptManager has a property named IsInAsyncPostBack to determine an AJAX call, the control is scoped to the page it is contained in.  If writing code in a custom HTTP module, what if I need to know in the BeginRequest event whether the current request is AJAX or JSON?

How nice it would be to simply ask the request if it is in the context of an AJAX or JSON call.  In Visual Studio 2008/2010, I can do just that.  With extension methods, I can add two new behaviors to the HttpRequest object.  Here are my desired methods:

 namespace Palermo4.Web.Extensions
{
    public static class WebExtensions
    {
        public static bool IsJson(this HttpRequest request)
        {
            return request.ContentType.StartsWith("application/json",
                StringComparison.OrdinalIgnoreCase);
        }

        public static bool IsAjax(this HttpRequest request)
        {
            return (request.Headers.Get("x-microsoftajax") ?? "")
                .Equals("delta=true", StringComparison.OrdinalIgnoreCase);
        }        
    }
}

The above methods simply return whether the content type of the request matches application/json (JSON call) or x-microsoftajax (AJAX call).

To make use of my new methods in the global.asax, I need to add using statement for the namespace the extension methods are contained in.

 using Palermo4.Web.Extensions; 

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {        
        if (!Request.IsAjax()  && !Request.IsJson() )
        {
            // this is not an AJAX or JSON request
        }
    }
}

I can also make use of this namespace in my web.config file as follows:

 <configuration>
  <system.web>
    <pages>
      <namespaces>
        <add namespace="Palermo4.Web.Extensions" />
      </namespaces>
    </pages>
  </system.web>
</configuration>

Now I can use my methods in any page as seen below:

page_request_isajax_isjson