When I tried for the first time WebAPI I asked to myself if I really need it instead of ASP.NET MVC because part of my own code (Controller Factory, Attributes, etc) doesn’t work as is. In these days I’ve started to do some experiments and, after that, I can say that we really need it for many reason, one of this is absolutely the content negotiation.
Take a look at the two code blocks below:
publicIEnumerable<string>Get(){returnnewstring[]{"value1","value2"};}[AcceptVerbs(HttpVerbs.Get)]publicActionResultGet(){returnJson(newstring[]{"value1","value2"},JsonRequestBehavior.AllowGet);}
As you can see these two code blocks are really similar except for two things:
- The attribute AcceptVerbs;
- The method Json() in the return statement;
In fact, if you look the code from another point of view, you can imagine that with the Web API there isn’t a direct connection from your code and the response type (JSON in this case).
With ASP.NET MVC the response will be always a JSON (in fact I specified it using the method Json()), in the second one there isn’t a connection to the JSON format, it means that you could have different responses without changing the Action, let’s try and see!
Let’s start to create a simple Web API application using the classic template, so follow the step below:
Without any change you are able to run the application: try by yourself by pushing F5 and navigating with a browser to the path “/api/values” of your website. If you are doing that with Internet Explorer, probably it will ask you to download the json response, otherwise if you open the same url with Chrome you can see the response inside the browser in XML format. With the same code you have two different serializations. That’s awesome.
How can this happen?
The response format depends from two values in the http header, Acceptand ContentType. If you change that (for example Accept: application/xml and Content-Type: application/json), you can have a different response as you saw opening the same url with two different browser.
Why is that so cool? Because you can have and create different response like the aforementioned XML or JSON without changing the code; plus, you can add other response type like Binary and CSV and you Action is still the same. I love it!
In the next posts I’ll show some helper to improve the response in Web API and how to create custom responses, so stay tuned!