Wednesday 28 March 2012

ASP.NET Web API Series - Part 1: Getting started...

[Level T1]

OK, in order to get started you may have a look at these excellent resources.

Alternatively, I will cover a little bit of background on how to get up and running.

FAQ

  • Where would I download it from? You may get it from here.
  • Do I need .NET Framework 4.5 to run it? No, it quite happily works with .NET 4.0. In fact if you have .NET 4.5 installed on your machine, you need to uninstall it.
  • Can I run it in Visual Studio 2010? Yes. In fact AFAIK it currently does not run in Visual Studio 2011.
  • Is it safe to install this on my main development machine? Most probably yes. I have not seen any problems so far and not aware of any problems reported.
  • How would I create a new Web API project? After installation, just go to Visual Studio 2010/Create new project and from "Web Projects" choose "ASP. NET MVC 4.0". You will be shown a menu from which you may select "Web API".
  • How easy is it to pick up ASP.NET Web API? If you are familiar with ASP.NET MVC, then very easy. If you come from a Web Forms or WCF background, you need to get up to speed with HTTP and REST fundamentals.

Hello World

Your ASP.NET Web API project comes with a sample controller called ValuesController. You may rename the class to HelloWorldController. An API controller is pretty much all you need to get it working now - more details below. Project also comes with standard MVC HomeController which will serve the home page.

So let's delete all the contents of the HelloWorldController and put the code below:

namespace GettingStarted.Controllers
{
 public class HelloWorldController : ApiController
 {
  // GET /api/HelloWorld
  public string Get()
  {
   return "Hello World";
  }

 }
}

OK, if you browse to http://localhost:<YourPortName>/api/HelloWorld, you will see this page:

Great! So we made our first ASP.NET Web API service. Now let' see how this magic work.

First of all, we see a controller, similar to MVC controller but it is inherited from System.Web.Http.ApiController rather than System.Web.Mvc.Controller.

Also you may notice that you can get to the home page using the base URL but for our Web API controller, we need to add "/api" to the base URL. This is simply a convention and can be overriden in global.asax:

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

Does it not look familiar? Yes, it is, almost the same as ASP.NET MVC routing. One difference is that we use MapHttpRoute instead of MapRoute. Welcome to the parallel universes! The other difference is that we do not define an action here.

So how the action gets defined? We used the name Get for our method name. This is not a co-incidence, this basically tells Web API to use this method for GET HTTP verbs. An alternative is to use [HttpGet] attribute and use any name for the method:

// GET /api/HelloWorld
[HttpGet]
public string AnyName()
{
 return "Hello World";
}

Above code works just the same. Now let's look why the data received back was XML? We did not define that we need XML. Well, it is because Chrome (this is the browser I use) sent this Accept header:


Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8


This will kick in the Content Negotiation and Web API chooses application/xml formatter and formats the data as XML. If we remove this header, here is what we get:


200 OK
Date: Wed, 28 Mar 2012 17:47:54 GMT
X-AspNet-Version: 4.0.30319
Transfer-Encoding: chunked
Connection: Close
Pragma: no-cache
Server: ASP.NET Development Server/10.0.0.0
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Expires: -1
"Hello World"

Note the JSON content-type. So basically the default formatter is JSON formatter which is the best choice.

Conclusion


Web API is very easy to get started with. In the heart of Web API we find the API controller.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.