Do we really need Web API instead of ASP.NET MVC?

By Ugo Lattanzi on July 3rd , 2012 in aspnetmvc WebAPI | comments

Share On Google Share On Facebook Share On Twitter

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:

public IEnumerable<string> Get() {
  return new string[] { "value1", "value2" };

public ActionResult Get() {
  return Json(new string[] {"value1", "value2"}, JsonRequestBehavior.AllowGet);

As you can see these two code blocks are really similar except for two things:

When I was thinking that I don’t need WebAPI I told to myself that calling a method and adding an attribute is not a big issue for a developer, but there is something more important to consider, the response content.

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, Accept and 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!