Getting Started With MVC4 and WebAPI in ASP.Net

The ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients, including browsers, phones and tablets.

Introduction

I've spent the last year working on ASP.NET MVC3 and I am feeling good this year about MVC4. I got some new and exciting features after updating to MVC4, the Web API is one of the exciting new features. I have read a lot on this feature and have read many good articles on the web. But I have not found an article that covers all the concepts in one place. So I have tried to combine them into one place for beginners. Please don't consider this article as my own invention, everything is taken from several articles. Please navigate the links in the History section for further details.

Prerequisites

  • ASP.NET MVC4.
  • You can also use the Web API on MVC3. Just install the WebAPI pieces using the Nuget Package Manager dialog.
  • Or use the Package Manager Console and type: Install-Package AspNetWebApi.

What is ASP.NET Web API

The ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients, including browsers, phones and tablets. You can use XML or JSON or something else with your API. JSON is nice for mobile apps with slow connections, for example. You can call an API from jQuery and use the client's machine and browser better.

This article shows the basic database operations (CRUD) in an HTTP service using the ASP.NET Web API. Many HTTP services also model CRUD operations using REST or REST-like APIs.



Why use ASP.NET Web API

The ASP.NET Web API is built for all the other, non-human interactions your site or service needs to support. Think about jQuery code that's making an Ajax request, or a service interface that supports a mobile client. In these cases, the requests are coming from code and expect some kind of structured data and specific HTTP Status Codes.

These two are very complimentary, but vary enough that trying to build HTTP services using ASP.NET MVC took a lot of work to get right. The inclusion of the ASP.NET Web API in an ASP.NET MVC (and availability elsewhere, including ASP.NET Web Pages) means that you can build top-notch HTTP services in an ASP.NET MVC application, taking advantage of a common base and using the same underlying paradigms.

Supported Features

The ASP.NET Web API includes support for the following features.

  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client using the new HttpClient type.
  • Full support for routes: Web APIs now support the full set of route capabilities that have always been a part of the Web stack, including route parameters and constraints. Additionally, mapping to actions has full support for conventions, so you no longer need to apply attributes such as [HttpPost] to your classes and methods.
  • Content negotiation: The client and server can work together to determine the right format for data being returned from an API. We provide default support for XML, JSON and Form URL-encoded formats and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects that can be used by the Web API actions.
  • Filters: Web APIs now support filters, including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
  • Query composition: By simply returning IQueryable<t>, your Web API will support querying via the OData URL conventions.
  • Improved testability of HTTP details: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage. Generic versions of these objects also exist to let you work with your custom types in addition to the HTTP types.
  • Improved Inversion of Control (IoC) via DependencyResolver: The Web API now uses the service locator pattern implemented by MVC's dependency resolver to obtain instances for many different facilities.
  • Code-based configuration: Web API configuration is accomplished solely using code, leaving your config files clean.
  • Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of the Web API.

How To Create a New Web API Project

Start Visual Studio 2010 and use the following procedure:

  1. Select New Project from the Start page/File menu then New Project.
  2. From the list of project templates, select ASP.NET MVC 4 Web Application. Select your preferred location then type your desired project name and click OK.
  3. In the New ASP.NET MVC 4 Project dialog, select Web API. The View engine will be Razor by default then click OK.



Add a Model

A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML or others. Then serialize and write the data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most of the clients are able to parse XML or JSON. By setting the Accept header in the HTTP request message the client can indicate which format it wants.

We will prove the preceding concepts step-by-step. Let's start by creating a simple model.

In Solution Explorer, right-click the Models folder then select Add then select Class.



Name the class Book. Next, add the following properties to the Book class.

  1. public int Id { getset; }  
  2. public string Name { getset; }  
  3. public decimal Price { getset; }  
Add a Repository

For serving our article's purposes, let's store the list in memory and the HTTP service needs to store a list of books.

Let's separate the book object from our service implementation. This is because we can change the backing store without rewriting the service class. This type of design is called the Repository pattern. For this purpose, we need a generic interface. Let's see the following procedure to understand how to define a generic interface for a book repository.

In Solution Explorer, right-click the Models folder. Select Add, then select New Item.

Then add another class to the Models folder, named "BookRepository" that will implement the IBookRespository interface derived from IBookRepository:

Following are the implementations:
  1. public interface IBookRepository   
  2. {  
  3.     IEnumerable < book > GetAll();  
  4.     Book Get(int id);  
  5.     Book Add(Book item);  
  6.     void Remove(int id);  
  7.     bool Update(Book item);  
  8. }  
  9. public class BookRepository: IBookRepository   
  10. {  
  11.     private BookStore db = new BookStore();  
  12.     public BookRepository() {}  
  13.     public IEnumerable < Book > GetAll()   
  14.     {  
  15.         return db.Books;  
  16.     }  
  17.     public Book Get(int id)   
  18.     {  
  19.         return db.Books.Find(id);  
  20.     }  
  21.     public Book Add(Book item)   
  22.     {  
  23.         db.Books.Add(item);  
  24.         db.SaveChanges();  
  25.         return item;  
  26.     }  
  27.     public void Remove(int id)  
  28.     {  
  29.         Book book = db.Books.Find(id);  
  30.         db.Books.Remove(book);  
  31.         db.SaveChanges();  
  32.     }  
  33.     public bool Update(Book item)   
  34.     {  
  35.         db.Entry(item).State = EntityState.Modified;  
  36.         db.SaveChanges();  
  37.         return true;  
  38.     }  
  39. }  

The repository will keep books in local memory. We already mentioned and we can compromise for the article purposes but in a real application please don't do it. Because you need to store data either in a database or in Cloud storage. The Repository pattern will make it easier to change the implementation later.

Add a Web API Controller

If you have worked with ASP.NET MVC, then you are already familiar with controllers. In the ASP.NET Web API, a controller is a class that handles HTTP requests from the client. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in the Solution Explorer.

HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site and is not directly related to our Web API service. ValuesController is an example WebAPI controller.

Since we want to start from scratch, go ahead and delete ValuesController. Do we need to specify how to delete? OK, right-click the file in Solution Explorer and select Delete.

Add a new controller

Then add a new controller as follows,

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.

In the Add Controller wizard, name the controller BooksController. In the Template dropdown list, select Empty API Controller. Then click Add.



The Add Controller wizard will create a file named BooksController.cs in the Controllers folder. If this file is not open already, double-click the file to open it.

Add the following using statements and add a field for holding an IBookRepository instance.

  1. using WebAPI.Models;  
  2. using System.Net;  
  3. public class BooksController: ApiController   
  4. {  
  5.     static readonly IBookRepository _repository = new BookRepository();  
  6. }  
Dependency Injection with IoC Containers

A dependency is an object or interface that another object requires. For example, in this article we defined a BooksController class that requires an IBookRepository instance. The preceding is what the implementation looks like.

This is not the best design, because the call to the new BookRepository is hard-coded into the controller class. Later, we might want to switch to another implementation of IBookRespository and then we would need to change the implementation of BooksController. It is better if the BooksController is loosely decoupled from any concrete instance of IBookRespoitory.

Dependency injection addresses this problem. With dependency injection, an object is not responsible for creating its own dependencies. Instead, the code that creates the object injects the dependency, usually using a constructor parameter or a setter method.

The following is a revised implementation of BooksController.
  1. public class BooksController: ApiController   
  2. {  
  3.     static IBookRepository _repository;  
  4.     public BooksController(IBookRepository repository)   
  5.     {  
  6.         if (repository == null)  
  7.         {  
  8.             throw new ArgumentNullException("repository");  
  9.         }  
  10.         _repository = repository;  
  11.     }  
An IoC container is a software component responsible for creating dependencies. IoC containers provide a general framework for Dependency Injection. If you use an IoC container, then you don't need to wire up objects directly in code. Several Open-Source .NET IoC containers are available. The following example uses Unity, an IoC container developed by Microsoft Patterns & Practices.

In Solution Explorer, double-click Global.asax. Visual Studio will open the file named Global.asax.cs that is the code-behind file for Global.asax. This file contains code for handling application-level and session-level events in ASP.NET.

Add a static method named ConfigureApi to the WebApiApplication class.

Add the following using statements
  1. using Microsoft.Practices.Unity;  
  2. using WebAPI.Models;  
  3. Add the following implementation: void ConfigureApi(HttpConfiguration config)   
  4. {  
  5.     var unity = new UnityContainer();  
  6.     unity.RegisterType < BooksController > ();  
  7.     unity.RegisterType < IBookRepository, BookRepository > (  
  8.     new HierarchicalLifetimeManager());  
  9.     config.DependencyResolver = new IoCContainer(unity);  
  10. }  
  11. Now modify the Application_Start method to call RegisterDependencies: protected void Application_Start()  
  12. {  
  13.     AreaRegistration.RegisterAllAreas();  
  14.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  15.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
  16.     BundleConfig.RegisterBundles(BundleTable.Bundles);  
  17.     ConfigureApi(GlobalConfiguration.Configuration);  
  18.     Database.SetInitializer(new BookInitializer());  
  19. }  
Getting Book

The book service will expose two "read" methods, one that returns a list of all books and another that looks up a book by ID. The method name starts with "Get", so by convention it maps to GET requests. Further, the method has no parameters, so it maps to a URI with no "id" segment in the path. The second method name also starts with "Get", but the method has a parameter named id. This parameter is mapped to the "id" segment of the URI path. The ASP.NET Web API framework automatically converts the ID to the correct data type (int) for the parameter.

Notice that GetBook throws an exception of type HttpResponseException if the ID is not valid. This exception will be translated by the framework into a 404 (Not Found) error.
  1. public IEnumerable < book > GetAllBooks()   
  2. {  
  3.     return _repository.GetAll();  
  4. }  
  5. public Book GetBook(int id)   
  6. {  
  7.     Book book = _repository.Get(id);  
  8.     if (book == null)   
  9.     {  
  10.         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));  
  11.     }  
  12.     return book;  
  13. }  



Creating a Book

To create a new book, the client sends an HTTP POST request, with the new book in the body of the request message.

The following is a simple implementation of the method:
  1. public Book PostBook(Book book)   
  2. {  
  3.     book = _repository.Add(book);  
  4.     return book;  
  5. }  
To handle POST requests, we define a method whose name starts with "Post...". The method takes a parameter of type Book. By default, parameters with complex types are deserialized from the request body. Therefore, we expect the client to send us a serialized representation of a Book object, using either XML or JSON for the serialization.

This implementation will work, but it is missing the following couple of things to complete. 
  • Response code: By default, the Web API framework sets the response status code to 200 (OK). But according to the HTTP/1.1 protocol, when a POST request results in the creation of a resource, the server should reply with status 201 (Created).
  • Location: When the server creates a resource, it should include the URI of the new resource in the Location header of the response.

The ASP.NET Web API makes it easy to manipulate the HTTP response message. Here is the improved implementation:

  1. public HttpResponseMessage PostBook(Book book)   
  2. {  
  3.     book = _repository.Add(book);  
  4.     var response = Request.CreateResponse < Book > (HttpStatusCode.Created, book);  
  5.     string uri = Url.Route(nullnew   
  6.     {  
  7.         id = book.Id  
  8.     });  
  9.     response.Headers.Location = new Uri(Request.RequestUri, uri);  
  10.     return response;  
  11. }  
Notice that the method return type is now HttpResponseMessage<book>. The HttpResponseMessage<t> class is a strongly-typed representation of an HTTP response message. The generic parameter T gives the CLR type that will be serialized to the message body. This was in the Beta version. You will get compilation errors. The new way to handle this is via the Request property in your controllers; you will need to change any return type from HttpResponseMessage<t> to HttpResponseMessage.

In the constructor, we specify the Book instance to serialize and the HTTP status code to return as in the following:
  1. var response = Request.CreateResponse<Book>(HttpStatusCode.Created, book);  


Updating a Book

Updating a book with PUT is straightforward. Simply define a method whose name starts with "Put...":
  1. public void PutBook(int id, Book book)   
  2. {  
  3.     book.Id = id;  
  4.     if (!_repository.Update(book))  
  5.     {  
  6.         //throw new HttpResponseException(HttpStatusCode.NotFound);  
  7.         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));  
  8.     }  
  9. }  
This method takes two parameters, the book ID and the updated book. The ID parameter is taken from the URI path and the book parameter is deserialized from the request body. By default, the ASP.NET Web API framework takes simple parameter types from the route and complex types from the request body.

Deleting a Book

To delete a book, define a "Delete..." method as in the following:
  1. public HttpResponseMessage DeleteBook(int id)  
  2. {  
  3.     _repository.Remove(id);  
  4.     return new HttpResponseMessage(HttpStatusCode.NoContent);  
  5. }  
According to the HTTP specification, the DELETE method must be idempotent, meaning that several DELETE requests to the same URI must have the same effect as a single DELETE request. Therefore, the method should not return an error code if the book was already deleted.

If a DELETE request succeeds, it can return status 200 (OK) with an entity-body that describes the status, or status 202 (Accepted) if the deletion is still pending, or status 204 (No Content) with no entity body. In this example, the method returns status 204.

Using the HTTP Service with JavaScript, jQuery and jQuery Template

In Solution Explorer, expand the Views folder and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Add the following code:
  1. < script type = "text/javascript" > $(function()   
  2. {  
  3.     $.getJSON(  
  4.         "api/books",  
  5.   
  6.     function(data)   
  7.     {  
  8.         $.each(data,  
  9.   
  10.         function(index, value)  
  11.         {  
  12.             $("#bookTemplate").tmpl(value).appendTo("#books");  
  13.         });  
  14.         $("#loader").hide();  
  15.         $("#addBook").show();  
  16.     });  
  17.     $("#addBook").submit(function()  
  18.     {  
  19.         $.post(  
  20.             "api/books",  
  21.         $("#addBook").serialize(),  
  22.         function(value)  
  23.         {  
  24.             $("#bookTemplate").tmpl(value).appendTo("#books");  
  25.             $("#name").val("");  
  26.             $("#price").val("");  
  27.         },  
  28.             "json");  
  29.         return false;  
  30.     });  
  31.     $(".removeBook").live("click"function()   
  32.     {  
  33.         $.ajax({  
  34.             type: "DELETE",  
  35.             url: $(this).attr("href"),  
  36.             context: this,  
  37.             success: function() {  
  38.                 $(this).closest("li").remove();  
  39.             }  
  40.         });  
  41.         return false;  
  42.     });  
  43.     $("input[type=\"submit\"], .removeBook, .viewImage").button();  
  44. });  
  45. function find()  
  46. {  
  47.     var id = $('#bookId').val();  
  48.     $.getJSON("api/books/" + id,  
  49.     function(data)   
  50.     {  
  51.         var str = data.Name + ': $' + data.Price;  
  52.         $('#book').html(str);  
  53.     })  
  54.         .fail(  
  55.   
  56.     function(jqXHR, textStatus, err)   
  57.     {  
  58.         $('#book').html('Error: ' + err);  
  59.     });  
  60. }  
  61. < /script>  


The presentation of data on the View looks as in the following:


The preceding examples demonstrate Get All Books, Add Book and Remove a Book from the list. The find function helps us to get a book by ID. For binding all the book lists we used the jQuery template over here. The following portion is also needed for that.
  1. < script id = "bookTemplate"  
  2. type = "text/html" > < li > Book Name: $   
  3. {  
  4.     Name  
  5. }  
  6. Price: $   
  7. {  
  8.     Price  
  9. } < a class = "button small red removeBook"  
  10. href = "$%7B%20Self%20%7D" > Remove < /a>  
  11.   
  12. </li > < /script>  
And the HTML should look like the following.

Hide Copy Code
  1. <div class="grid_16 body-container">  
  2.     <div class="margin grid_6 alpha">  
  3.         <label for="Name"> Name</label>  
  4.         <input type="text" class="text grid_4" name="Name" id="name" />  
  5.         <label for="Price">Price</label>  
  6.         <input type="text" class="text grid_4" name="Price" id="price" />  
  7.         <input type="submit" class="button small green" value="Add" />  
  8.         <label for="bookId">Serach By ID</label>  
  9.         <input type="text" class="text grid_4" size="20" id="bookId" />  
  10.         <input type="button" class="button small gray"  
  11. önclick="find();" value="Search" />  
  12.         <label id="book"></label>  
  13.     </div>  
  14.     <div class="grid_8 omega">  
  15.         <ul class="books" id="books"></ul>  
  16.     </div>  
  17. </div>  
We have used the jQuery template for making the right site book list. Please download the source code for more details.

Points of Interest
  1. Full support for Routes.
  2. Model binding.
  3. Filters.
  4. Content negotiation.
  5. Bundling by default.
  6. oData style query support.
  7. Razor enhancements.
  8. URL resolution: Support for ~/ syntax.
  9. Conditional attribute rendering.
  10. NuGet based project installation.

And many more...

History

I have taken all the concepts/a few contents from the following.

I hope you all enjoyed what I described. Thanks for reading the article. Have fun.

Up Next
    Ebook Download
    View all
    Learn
    View all