1

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"?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • Note: If I'm reading correctly, the Content-Type header specifies the format of the **request** - it has nothing to do with what the client expects got get - that would be the Accept header: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields – Kobi Mar 22 '12 at 08:15

3 Answers3

5

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");
}
Community
  • 1
  • 1
Lance McNearney
  • 9,410
  • 4
  • 49
  • 55
4

I was having the same issues but for whatever reason jQuery's $.get was not sending a Content Type. Instead I had to check in the Request.AcceptTypes for "application/json."

Hope this helps others with the same problem in the future.

Jeff
  • 340
  • 1
  • 4
  • 16
0

As it is a private API, you have control over the content type for JSON, so simply check it is the agreed value.

e.g.

public static bool IsJsonRequest(this HttpRequestBase request)
{
  bool returnValue = false;
  if(request.ContentType == "application/json")
  returnValue = true;

  return returnValue;            
}
Ben Aston
  • 53,718
  • 65
  • 205
  • 331