Building Asp .Net MVC Web API From Scratch
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.
- Understanding Asp .Net MVC Web API
- Basic AJAX CRUD operations using jQuery and Web API -Part I
- Basic AJAX CRUD operations using jQuery and Web API -Part II
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.
Next, let's create a new Asp .Net MVC 4 empty API project.
Adding an API Controller
Next let's add a new Contacts Controller, by using the API Controller scaffolding template.
Doing this should create a Controller similar to below. This generates basic Get/Put/Post/Delete ActionMethod operations in a new Contacts 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.
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.
Internet Explorer gets data back in Json format and we will try opening the file in notepad to see the data.