ASP.NET, determine if a request content type is for JSON

asp.netcontent-typejson

I'd like to implement an extension method IsJsonRequest() : bool on the HttpRequestBase type. In broad terms what should this method look like and are there any reference implementations?

This is a private API.

Edit:

Suggestion; check if the x-requested-with header is "xmlhttprequest"?

Best Answer

This will check the content type and the X-Requested-With header which pretty much all javascript frameworks use:

public bool IsJsonRequest() {
    string requestedWith = Request.ServerVariables["HTTP_X_REQUESTED_WITH"] ?? string.Empty;
    return string.Compare(requestedWith, "XMLHttpRequest", true) == 0
        && Request.ContentType.ToLower().Contains("application/json");
}