Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to detect a JSON request on ASP.NET

Tags:

Most ajax frameworks seem to standardize with "X-Request-With" on either a header or the query string.

And in ASP.NET MVC you can use the extension method

Request.IsAjaxRequest()

Because an ajax client can request several different content types, not just "application/json" ex: "application/xml".

I'm using the following code snippet/extension method, but I would love to see what others are doing or if there is something I missed, or a better way.

public static bool IsJsonRequest(this HttpRequestBase request)
{
    return request.Headers["Accept"].Split(',') 
       .Any(t => t.Equals("application/json", StringComparison.OrdinalIgnoreCase));
}

Thanks in advance.

like image 625
Dax70 Avatar asked Jun 03 '11 04:06

Dax70


People also ask

How does ASP net handle requests?

ASP.NET is a request processing engine. It takes an incoming request and passes it through its internal pipeline to an end point where you as a developer can attach code to process that request. This engine is actually completely separated from HTTP or the Web server.


1 Answers

You should be using the request's accept header for this. This indicates what type of content the client wants the server to send to it.

Do not use the request's content type header - this indicates is the type of the body of the request message. By all means set it to "application/json" if you are POSTing or PUTting some Json to the server, but if you are making a GET request then the content type should be empty ( as the body of a GET request is empty ), and if you are posting a multi-part form or something else then it should reflect that type.

The behaviour for forms on web is to set the request content type to 'multipart/form-data' and the accept type to 'text/html'. On the web, overloading the server so that it returns the same type as the request content type whilst ignoring the accept type header would mean that posted forms return encoded form data rather than an html page. This obviously is not the correct behaviour, so don't build your applications around such an interpretation of the request content type.

like image 133
Pete Kirkham Avatar answered Oct 24 '22 15:10

Pete Kirkham