Building Asp .Net MVC Web API From Scratch

Aug 21, 2013
Download Source

In this blog post we will start creating the basic Asp .Net MVC Web API sample. There are bunch of blog posts I have been making around this topic. So in case you are looking for what this new platform is and how it is different from other service building frameworks out there, please look at the following post.

So, let's jump right into building a basic ContactManager API. To follow along with this tutorial you will be using,

Creating The Empty Solution

As the goal of Web API is to keep things simple and as minimum as possible, let's start from creating and Empty solution.

Empty Solution

Next, let's create a new Asp .Net MVC 4 empty API project.

MVC 4 Project

MVC 4 Empty Project

Adding an API Controller

Next let's add a new Contacts Controller, by using the API Controller scaffolding template.

Add API Controller

Doing this should create a Controller similar to below. This generates basic Get/Put/Post/Delete ActionMethod operations in a new Contacts controller.

Add API Controller

Now let's examine where we are setting up routes for this API controller. As you look at your project folder App_Start, you find a file called WebApiConfig that contains following route.

API route

Web API project

And this function is being invoked at the application start in the Global.asax to register the route.

Testing the Web API

Next,let's go ahead and run the application. First, it should throw a 404 error because it is not finding the Index view in the Home controller, which is the default Route for the application when nothing is passed in the URL.

Let's just put /API/Contacts at the end of the URL and try running the application in Google Chrome and Internet Explorer.

By default, Google chrome will get data back in XML format.

Chrome Data

Internet Explorer gets data back in Json format and we will try opening the file in notepad to see the data.


JSON data