Introducing the ASP.NET Web API

Posted by Filip Ekberg on March 19 2012 8 Comments

In the new version of ASP.NET you can use something called ASP.NET Web API. This allows you to expose your data in many different formats, such as XML or JSON. The idea is to provide a REST API where you use HTTP for real. Meaning that you use GET/POST/PUT/DELETE. These work pretty straight forward:

  • GET – Retrieve all or one item
  • POST – Add an item
  • PUT – Update an item
  • DELETE – Remove an item

As mentioned above, you can retrieve data in different formats such as XML or JSON. The type of data that will be in the response is determened by the HTTP header Accept. By default(built-in) you can use the two following accept headers:

  • application/json
  • applicaiton/xml

In order to try this out, I will be using curl to make the web requests, because this will allow me to specify the headers manually.

Start off by creating a new ASP.NET MVC 4 Web Applicaiton in Visual Studio 11 Beta:

Then you will be presented with what kind of ASP.NET MVC 4 project that you want to create, select to create a new Web API project:

When the project is created, you’ll have some new things that you haven’t seen before in a normal ASP.NET MVC application. It does look a lot like a normal ASP.NET MVC applications, but with some minor add-ons.

The first thing that we are presented with is the ValuesController and this controller inherits from the ApiController. The ApiController is what you will inherit from when you are creating API specific controllers. It will help you map the HTTP requests GET/POST/PUT/DELETE to the methods with the corresponding names.

The second thing that is added is inside the global.asax.cs, a new route to specify where we retrieve the API specific controllers:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

This just help us distinguish between our API calls and non-API calls. If you just start the web application and navigate to /api/values/ you will see a list like this:

If we open this in Internet Explorer 10 instead, it will request a JSON result instead of XML and if we open that up in notepad, it looks like this:

We can verify that this works by testing it out with curl.

Get JSON using curl

curl -H "Accept: application/json" -H "Content-Type: application/json" -X GET "http://localhost:13938/api/values"

JSON Result:

["value1","value2"]

Get XML using curl

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET "http://localhost:13938/api/values"

XML Result:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>

This is good and all, but we might want to be able to specify what kind of format that we expect with a query string. To do this, we can register a formatter for a certain query string mapping. Go back to global.asax.cs and add the following at the end of Application_Start:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

This will allow you to add ?type=json or ?type=xml to request a certain output format:

If you want to retrieve a specific item, you can simply do /api/values/1.

This has been a short introduction to get you started with the ASP.NET Web API. If you found this interesting, stay tuned for the live stream that I will do from Webbdagarna (if the Internet connection allows) and also stay tuned for upcoming posts where we hook up with Entity Framework to make this API more alive.

Vote on HN

8 Responses to Introducing the ASP.NET Web API

  1. Eric IrwinNo Gravatar says:

    Great Post! I have been wondering when Microsoft was going to do something like this. This just seems like another step in the right direction for allowing distributed, service based architectures. Of course, this could be done with MVC 3, but it seems they have taken the necessary steps to distinguish the use of the ASP.NET Web API over MVC. I haven’t looked too much into this API yet. Does it allow you to integrate the Web API into an existing MVC 4 application, or does it have to be contained in a separately defined site?

  2. Filip EkbergNo Gravatar says:

    Hi Eric,

    Thank you!

    Yes, you can use this in a standard MVC 4 Web Application, it’s just that you get some prepared controllers and references to get you started.

  3. Ben HoffmanNo Gravatar says:

    Excellent post! As I learn more about Microsoft’s Web API, it seems like it has some overlap with Microsoft’s WCF technology. Is it replacing it, or is it just something that has some overlap or does it work with it?

  4. Filip EkbergNo Gravatar says:

    I would say that it is an alternative way to expose your data. Using WCF gives you tons of configuration possibilities regarding for instance security.

    While ASP.NET Web API on the other hand makes it much easier to expose your data in different formats depending on what the consumer wants (xml/json/protobuf).

    I think they just have features that overlap and both have different, sometimes the same, use cases.

  5. David KempNo Gravatar says:

    Does this support JSONP? JSON’s nice enough, but JSONP is still a necessary evil until everyone has upgrade their browser (which doesn’t look like it’s going to happen any time this millenium)

  6. Filip EkbergNo Gravatar says:

    The simple answer is no, not out of the box. At least not as far as I can see by browsing the source code.

    Web API essentially uses the requested content-type to determine what kind of data to return and JSONP is the same content-type as JSON. But what you can do is to have a handler that just wraps around the api.

    Does that make sense?

  7. Ali RobertsonNo Gravatar says:

    Rather than using CURL, you can get a couple of Chrome extensions: JSONView and “Change HTTP Request Header”, which you can use to override the “Accept” header to application/json.

  8. Maarten JansoniusNo Gravatar says:

    Cool! When using the XML results, is there any way to request the XSD of the resultset?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>