.NET Zone is brought to you in partnership with:

I am a Software Engineer working with the latest in .NET focusing on Web Development. With a burning heart for programming, I blog and author a book about C#. Filip is a DZone MVB and is not an employee of DZone and has posted 54 posts at DZone. You can read more from them at their website. View Full User Profile

Introducing the ASP.NET Web API

03.19.2012
| 5185 views |
  • submit to reddit

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.

Published at DZone with permission of Filip Ekberg, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)