Creating and Consuming Web API in ASP.NET MVC


Asp.Net application development Indian team have intended this post to explain how to create and consume Web API in ASP.Net MVC application. You can follow the instruction shared by them and perform the same process at your place.

Before we start a development using a Web API framework it is extremely important to understand what it’s purpose, and how it’s works.

For those who doesn’t know what it is, a Web API is a set of pre-defined messages of request and response (between server and client) through HTTP, which are generally expressed in XML or JSON formats.

All of us had already a contact with some kind of web service of that kind (not necessarily built with Web API), could it be a web site you use on daily basis, or some of our preferred applications installed on our smartphone. An example of such application are Facebook, Twitter, Linkedin or event games may use Web API. So, if you want to start a new project probably you may use this way of thinking about web services.

For you to better understand Web API functionalities, I will describe it in a simple example for you to understand how Web API works, like for an example, one that is used with your Twitter application. Given that is installed within your smartphone:

  • You input your login data;
  • The application saves locally you credential and send them to the authentication server in order to generate the authentication Token;
  • If the data entered is invalid for login, the error is returned, if the all data is valid then the token is returned to the application;
  • The authentication token will be send in all following communication with the server will (until its expires), in order to make sure you are already logged in.

Web API Authentication

In order to learn more about the details of Web API functioning, you may visit the official web site and take a look at the tutorials.

So let’s get hands to work, let’s open a visual studio and create a new project. The use of visual studio is obvious on my opinion, this is free (community edition) and also its proprietary Microsoft tool to work with their technology.

First of all, open the visual studio and click the menu and then File -> New -> Project and create a project using the ASP.NET Web. Define the name and the path for your project. In my case it’s simply AspNetWebAPIMVCProject.

After clicking OK in the wizard, the new window will open to select details of our ASP.NET MVC Application. There you may define templates like WebForms, MVC, Web API, Single Page Application and others… In our case, we must select the empty template so we may only add the structure and libraries of our interest, which are actually important for our project.

Let’s take a look at some projects that we must include to our project.

Microsoft.Net.Http, Microsoft.AspNet.WebApi.Core, Microsoft.AspNet.WebApi.Owin, Microsoft.Bcl.Build, Microsoft.Bcl.Compression, Microsoft.Owin,Microsoft.Owin.Cors, Microsoft.Owin.Host.SystemWeb, Microsoft.Owin.Security, Microsoft.Owin.Security.OAuth, Newtonsoft.Json.

Now that you know what libraries to use, let’s start to install all of them. For that purpose, we will use a Nuget provided by Visual Studio.

We have 2 ways to include libraries by Nuget. One is using the Package Manager Console and another one is to use Manage Nuget Package for Solution option. I prefer use the second one, although in order to learn and to speed up our coding, I will be doing everything using the first described way to include libraries.

Open the Package Manager Console and write the following code there in order to install all of the packages. You must run the Install-Package command for all of the packages mentioned above and also for every package that you will decide to use in your application or every dependency required.

After executing all the libraries, we will end up with a complete list of libraries and their dependencies.

In order to be able to start using our Web API and to start implementing routes, we should create a class of Startup which will be responsible for initialize our project and all configurations needed. In the root our project (csproj folder) create a new class called Startup.cs. For that click with the right button of mouth over the project and select Add -> Class.


And then you must insert the following code to the class





publicclassStartup {

publicvoid Configuration(IAppBuildermyApplication) {

varcng = newHttpConfiguration();

varfrs = cng.Formatters;


var sets = frs.JsonFormatter.SerializerSettings;

sets.Formatting = Formatting.Indented;

sets.ContractResolver = newCamelCasePropertyNamesContractResolver();

frs.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;



        name: "DefaultRoute",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }






What the code does is to remove the XML format and add the JSON format, and also defining the map of our routes.

Create a new folder at the root of the project with the name Controllers. In this folder we will add controllers for our application.

Click with the right button of mouth over the folder created and select Add -> Controller.

In the new window, choose the option “Scaffold Web API 2 Controller – Empty”.

Define the name for your controller. I suggest to call it something like DefaultController


With the controller created, we will create some methods for our controller and will define routes there.


Basically the WebAPI controller would be very same as ASP.NET MVC controller, with the only difference is that in MVC you returning HTML to the client side, while Web API returns the data in json or xml formats. But at the end we are talking about the very same technologies which also may be used in conjunction with each other.

Now define the RoutePrefix for the controller, should look like the following code


In the example above we defined that when we call the url with the prefix api/test, ASP.NET will redirect request to that controller.

Now create a method like following:


publicclassDefaultController: ApiController




publicHttpResponseMessageGetServerTime() {

try {

var dh = DateTime.Now.ToString();

       //retrieves 200 status

returnRequest.CreateResponse(HttpStatusCode.OK, dh);


catch(Exception ex) {

       //retrieves 400 status

returnRequest.CreateResponse(HttpStatusCode.BadRequest, ex.Message);




As you can see in the above exemple, we created a method which will make a GET request with a route of datetime/availability which by the end will return the data when we call the following url:


Also in the example above we are defining the catch which will add error messages to the response object and also defining that response with the code 400 (BadRequest)


Here you’ve learned how to use Web API and how its related with the ASP.NET MVC, you will easily continue by investigating better the .NET framework documentation.

In the next part of this series we will see how to connect your Web API to the Data Base and how the resources should be shared between both ASP.NET Web API and ASP.NET MVC.

Please note that the coding shared by application development India team is for reference purpose only. If you have any doubt or want to ask anything related to the issue, make comments below.

You might like

We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.