WEB API Tutorial

Facebooktwitterredditpinterestlinkedinmailby feather


ASP.NET Web API is used for performing HTTP services that can be accessed by cross-platform clients on different applications, including such as web, windows, mobile, etc. ASP.Net Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications. It works more or less the same ways as ASP.NET and without it, MVC web applications send data as a response preferably of html views. It is like a web service or WCF service but the limitation is that it only supports HTTP protocol.


Web API Index

• Introduction of WEB API
• Why use WEB API
• Features of WEB API
• WEB API Version history
• Asp.Net Web API VS Asp.Net MVC
• Create a Web API project
• Web API Controller
• Web API Controller Characteristics
• Action Method Name for each HTTP Methods
• Difference between Web API and MVC controller
• Description of Web API hosting infrastructure and components
• Web API Routing
• Method List of MapHttpRoute();
• Action Method Return Type
• Data Formats of Web API
• Web API Filters
• HttpClient
• Web API Hosting

Why use the Web API

Currently, most mobile devices, browser and tablets are the media for accessing most of the internet applications and out of all this also people are mostly using mobile apps to add data to applications. But now we are going to use the Microsoft’s new technology called Web API.

Web API Features

  1. Supports convention-based CRUD actions, since it works with HTTP verbs GET, POST, PUT and DELETE.

            GET (Read)

            Retrieves the representation of the resource.


            Update an existing resource.

            POST (Create)

            Create a new resource.

            DELETE (Delete)

            Delete an existing resource.

2. Accept header and status code for HTTP responses.

3. ASP.NET Web API is a perfect platform for building RESTful services.

4. Supports multiple text formats like XML, JSON, etc. or you can use your custom MediaTypeFormatter.

5. It supports Self-hosting or IIS Hosting.

6. It supports the ASP.NET MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection.

Web API Version History

The following versions of ASP.NET Web API are released:

Web API 1.0

  • .NET Framework 4.0
  • VS 2010

Web API 2.0

  • .NET Framework 4.5
  • VS 2012, 2013

Asp.Net Web API VS Asp.Net MVC

S. No. Asp.Net Web API Asp.Net MVC
1. Asp.Net Web API is used for generating the HTTP services that respond only as data. Asp.Net MVC can use the MVC for developing the Web application that replies view and data.
2. The Web API returns the data in various formats, such as JSON, XML and other formats based on the accept header of the request. But the MVC returns the data in the JSON format by using JSONResult.
3. Web API supports content negotiation, and self-hosting. MVC does not support any of these.
4. The Web API helps the creation of RESTful services over the .Net Framework. MVC does not support.
web api tutorial

Create a Web API project

There are two ways to create a Web API project.

  1. Web API with MVC Project.
  2. Stand-alone Web API Project.

Web API with MVC Project

Visual Studio includes a Web API template which creates a new Web API project with ASP.NET MVC application.

Open Visual Studio for this, click the File menu and click New Project. As shown below, this will open the New Project popup.

Open Visual Studio

Now, select ASP.NET Web Application template in the middle pane and enter the name of a project and click OK. This will open New ASP.NET Project popup as shown below.

open New ASP.NET Project popup as

Select Web API in the above popup.

Important: Notice that we have selected and disabled MVC and Web API checkboxes, which means that it will add essential folders and sources for both MVC and Web API.

Click OK to create a new Web API and MVC project as shown below.

Click OK to create a new Web API and MVC project

This project is similar to the default MVC project with two particular files for Web API, WebApiConfig.cs in App_Start folder and ValuesController.cs in the Controllers folder as shown below.

WebApiConfig.cs in App_Start folder


The WebApiConfig.cs is a configuration file for Web API. In WebApiConfig.cs file you can configure the routes for web API, same as RouteConfig.cs is used to configure MVC routes. It also creates the Web API controller i.e. ValuesController.cs by default. After that, you can create Web API project with MVC to get started with your applications.

Stand-alone Web API Project

  • Now, we create a stand-alone Web API project without MVC project.
  • For this, open Visual Studio for Web and go to File menu and select New Project. This will open New Project popup as below.
go to File menu and select New Project.
  • Select Web template in the left pane and choose ASP.NET Web Application in the middle pane and Enter the name of the project, location and Another name(Solution name) as shown above and click on OK.
choose ASP.NET Web Application in the middle pane
  • Now, select Empty as a template and click OK. That will create an empty “HelloWebAPI” project.
  • Then, we will be needed to add the latest Web API sources using the NuGet Package Manager, and for that Right Click on the project and click Manage NuGet Packages.. as shown below.
click Manage NuGet Packages.. as shown below.
  • This will open Manage NuGet Packages popup. Select Online in the left sheet and search for web API (ensure that web association is on). This will show all the Internet Programming interface related packages. Select Microsoft ASP.NET Web API2.2 bundle and snap is given below.
Select Microsoft ASP.NET Web API2.2 bundle

These web packages are Displayed After Installation of WEB API  Packages.

web packages are Displayed After Installation of WEB API
  • After the Installation, create Controllers and Configuration folder in the HelloWebAPI project. Then We will add Web API controller in the Controllers folder and configuration class in the Configuration folder.
Web API controller in the Controllers folder and configuration class
  • Now, add a new class in the config folder and name it same as the Empty template name “HelloWebAPIConfig” with the following content. (You may give an appropriate name)

Example: Web API Configuration

  • Now, add Global.asax by right-clicking on the project -> select Add -> click New Item.. to open Add New Item popup as below. Select the Global Application Class and click OK.
Select the Global Application Class
  • Now, Global.asax will be added to the Project. We need to Config. Web API routes when applications are in execution. So call HelloWebAPIConfig.Register() method in the Application_Start event in the Global.asax as shown below.
  • Now, let’s add Web API controller by right clicking on the Controllers folder and select Controller. this will open popup as below.
Controllers folder and select
  • Select Web API in the left pane and Web API 2 Controller – Empty in the middle panel and click Add. This will open another popup to enter the name of your controller as below. Enter the controller name and click Add.
Enter the controller name and click Add
  • It will create a following empty HelloController class in Controllers Directory.

Example: Web API Controller

  • Now, we need to add action methods.

Example: Web API Controller

  • Now, compile and run the Project and drive to “http://localhost:xxxx/api/hello” in the browser.
compile and run the Project

In this way, you can create a simple Web API from scratch with config and controller class.

Web API Controller

Web API Controller is the same as MVC Controller. It manages incoming HTTP requests and sends Acknowledgement back to the caller.

Web API controller is a class that can be created under the Controllers folder or any other directory under your project’s root folder. The name of a controller class must be ended with “Controller” and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.

Example: Simple Web API Controller

In this Example, the ValuesController class is derived from ApiController and include multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.

Based on incoming request URL and HTTP verb GET/POST/PUT/PATCH/DELETE  Web API determines which Web API controller and action method to execute e.g. 

Get() method will handle the HTTP GET request.

Post() method will process HTTP POST request.

Put() method will handle the HTTP PUT request. 

Delete() method will process the HTTP DELETE request for the above Web API.

Web API controller and action method

Web API Controller Characteristics

  1. It must be obtained from the System.Web.Http.ApiController class.
  2. It can be created under any directory in the project’s root directory. However, it is recommended to develop controller classes in the Controllers folder as per the convention.
  3. The name of the Action method can be the same as the HTTP verb name.
  4. The return type of an action method can be any primitive or complex type.

Action Method Name for each HTTP Methods:-

1.HTTP Method:-GET 

Possible Web API Action Method Name:-





Usage:- It uses for Retrieves the Data.

2.HTTP Method:-POST

Possible Web API Action Method Name:-





Usage:-It uses forInserts new record.

3.HTTP Method:-PUT

Possible Web API Action Method Name:-





Usage:-It uses forUpdates existing record.

4.HTTP Method:-PATCH

Possible Web API Action Method Name:-





Usage:-It uses forUpdates record partially.


Possible Web API Action Method Name:-





Usage:-It is used toDelete the Records.

Difference between Web API and MVC controller

  1. Web API Controllers Receives from System.Web.Http.ApiController class, but MVC Controller Receives from System.Web.Mvc.Controller class.
  2. Method name in Web API must be started with Http verbs otherwise apply http verbs attribute, but in case of MVC Controller, Method name must be applied in an appropriate Http verbs attribute.
  3. Web API Controllers is specialized in returning data, whereas MVC Controllers is specialized in rendering view.

Configure Web API

Web API maintains a code-based configuration. It cannot be configured in web. Config file. We can configure Web API to customize the way of Web API receiving infrastructure and elements such as routes, formatters, filters, DependencyResolver, MessageHandlers, ParamterBindingRules, properties, services etc.

Now, We will create an easy Web API project in the Create Web API Project section. Web API project involves default WebApiConfig class in the App_Start Directory and also involve Global.asax.

solution explorer

Configure Web API

The Process of Web API Configuration starts when the Application starts. It calls GlobalConfiguration.Configure(WebApiConfig.Register) in the Application_Start method. The Configure() method demands the callback method where the Web API has been configured inside the code. By default, this is the static WebApiConfig.Register() method.

Description of  Web API hosting infrastructure and components

  1. DependencyResolver:- Gets or sets the province(dependency) resolver for province injection.
  2. Filters:-Gets or sets the filters.
  3. Formatters:- Gets or sets the media-type formatters.
  4. IncludeErrorDetailPolicy :- Its Valueindicate whether error details should be entered in error message or not.
  5. MessageHandlers:-Gets or sets the message handlers.
  6. ParameterBindingRules:-Gets the collection of rules for how parameters should be bound.
  7. Services:- Gets the Web API services.

Web API Routing

Web API Rout two types of routing:

  1. Convention-based Routing.
  2. Attribute Routing.

Convention-based Routing

Web API uses route templates to determine which controller and action method to execute. At least one route template must be added to the routing table to handle various HTTP requests.

Example: WebApiConfig with Default Route

Here, WebApiConfig.Reg() method, config.MapHttpAttributeRoutes() enables attribute routing.

The config. Routes is a routing table or route combination of type HttpRouteCollection. The “DefaultName” route is added in the route table using MapHttpRoute() extension method. The extension method of MapHttpRoute creates a new instance of IHttpRoute internally and adds it to a list of HttpRouteCollection.

Example: Add Default Route

Method List of MapHttpRoute( );

Name:-  Name of the route.
RouteTemplate:- URL pattern of the route.
Defaults:-  An object parameter that includes default route values.
Constraints :-   Regex expression to specify characteristic of route values.
Handler:-   The handler to which the request will be dispatched.

Action Method Return Type

These are some WEB API methods which can have the following return types.

  1. Void
  2. primitive type or Complex type
  3. HttpResponseMessage
  4. IHttpActionResult


Void is a Function that does not return any value after the function execution. 

Example: Void Return Type:-

Primitive or Complex Type

 A Primitive is a unified, immutable object, while a complex object contains other objects, both primitives and complex objects. The object itself is considered as a primitive because you can’t access the individual attributes of a complex object without casting first.

Example: Primitive or Complex Return Type:-


Web API controller always delivers an object of HttpResponseMessage to the hosting infrastructure. The following design illustrates the overall Web API request/response pipeline.

design illustrates the overall Web API requestresponse pipeline


Example: Return HttpResponseMessage


The IHttpActionResult is an action method in Web API 2 that can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.

Example: Return IHttpActionResult Type using Ok() and NotFound() Methods

Data Formats of Web API

A media type, is also called as MIME type, recognizes the format of a piece of data. In HTTP, media types explain the format of the message body. In the HTTP request, MIME type is defined in the request header using Accept and Content-Type attribute. The Accept header attribute specifies the format of acknowledged data which the client expects and the Content-Type header attribute specifies the format of the data in the request body so that the receiver can parse it into an suitable format. For example:

  • text/html
  • image/png
  • application/JSON

If a customer wants response data in JSON format then it will send following GET/POST HTTP request with Accept header to the Web API.

  • HTTP GET Request:
  • HTTP POST Request:

Example: Post Action Method

Here, the Post() action method accepts Employee type parameter, saves that employee into DB and returns inserted employee with generated id.

Web API Filters

Filters are  used to extract the code, which can be reused to make our actions cleaner and maintainable. Filters are actually attributes that can be used on the Web API controller or one or more action methods. Some filters are already provided by ASP.Net Core like the authorization filter, and they work as custom ones that we can create ourselves.

  •  Authorization filters – It forces the user to be authenticated before the action method run. 
  • Resource filters – Use for caching and execution,  they run after the authorization filters.
  • Action filters –They execute right before and after the action method execution.
  • Exception filters – It is Useful to handle unwanted errors or exceptions.


 Example:- Apply Web API Filter on Controller


 HTTP protocol is used  to interact with the webserver. HttpClient is a part that acts as an HTTP client for .NET applications. It uses the HttpClient class in a console application to send data to and receive data from Web API which is hosted on the local IIS web server.

Example:- Web API Controller

Step 1:- First, create a console application in Visual Studio 2015 for Desktop.

Step 2:- Open NuGet Package Manager console from TOOLS and NuGet Package Manager and Package Manager Console and execute the following command.

Install-Package Microsoft.AspNet.WebApi.Client 

Step 3:– Now, create a Student model class because we will send and receive a Student object to our Web API.

Example:- Model Class

Send GET Request

The following example sends an HTTP GET request to Employee Web API and displays the result in the console.

Example:- Send HTTP GET Request using HttpClient

Here is the list of all HttpClient methods to send different HTTP requests:

Method Name Description
GetAsync:-  It works as an asynchronous process, it sends a GET request to the defined Uri(Uniform Resource Identifier).
GetByteArrayAsync:-   It returns the response body as a byte array in an asynchronous operation when It Sends a GET request to the defined Uri.
GetStreamAsync:-  Sends a GET request to the defined Uri and returns the response body as a stream in an asynchronous operation.
GetStreamAsync:-  Sends a GET request to the defined Uri and returns the response body as a stream in an asynchronous operation.
PostAsync:-  Sends a POST request to the defined Uri as an asynchronous operation.
PostAsXmlAsync:-  Sends a POST request as an asynchronous operation to the defined Uri with the given value serialized as XML.
PutAsync:-  Sends a PUT request to the defined Uri as an asynchronous operation.
PutAsXmlAsync:-  Sends a PUT request as an asynchronous operation to the defined Uri with the given value serialized as XML.  
DeleteAsync:-  Sends a DELETE request to the defined Uri as an asynchronous operation.

Web API Hosting

There are two ways to Host Web API Application.

  • IIS Hosting
  • Self Hosting
two ways to Host Web API Application

IIS Hosting

IIS Hosting is known as Internet Information Services. It helps the HyperText Transfer Protocol (HTTP), File Transfer Protocol (FTP), Simple Mail Transfer Protocol (SMTP) etc.

Self Hosting

You can host a Web API as a separate process than ASP.NET. It means you can host a Web API in a console application or windows service or OWIN or any other method that is managed by the .NET framework.

These are the following steps for self-hosting of a web API.

  1. HttpConfiguration is used to configure a Web API
  2. Create HttpServer and start for incoming http requests listening.

Here You can see, how to host a simple Web API in console application.

Important Note:-  

Step 1:- You must open Visual Studio in Administration mode.

open Visual Studio in Administration mode.

Step 2:- You need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet.

You need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet.

Step 3:- Install Microsoft ASP.NET Web API 2.2 Self Host package from the list of all the packages for Web API. 

list of all the packages for Web API.

Click on Accept Button in the License Acceptance window.

Click on Accept Button in the License Acceptance window.

This will install the package into your  project.

install the package into your  project.

Now write the following code in the Main() method of Program class.

Example:- Self-Hosting Web API

Create My WebAPIMessageHandler class and write the following code.

Example: MessageHandler

MyWebAPIMessageHandler :HttpMessageHandler { protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)     { var task = newTask <HttpResponseMessage>(() => { var resMsg = newHttpResponseMessage();             resMsg.Content = new StringContent (”Hello World! “ ); return resMsg;         });         task.Start(); return task;     } } [/crayon]

Thus, you can create simple console application and host si

mple Web API that returns “Hello World!” to every request.

Run the console application using Ctrl + F5.

 console application using Ctrl

Open web browser and enter http://localhost:1447/ and see the result.

Open web browser

Hosting Controller Infrastructure

You can use the same ASP.NET routing and ApiController capabilities of ASP.NET Hosting in self hosting.

In the same self hosting console application, create simple HomeController class as shown below.

Example: Web API Controller

class HomeController : ApiController {     public string Get() {         return “Hello World!”;     }       public string Get(string name) {         return “Hello ” + name;     } } [/crayon]

Now, in the Main() method, configure a default route using config object as shown below.

Example: Self Hosting Web API

Important Note:- when creating an object of HttpSelfHostServer we removed an object of MessageHandler.

Now, run the console application by pressing Ctrl + F5. 

Open the browser and enter http://localhost:1447/api or http://localhost:1447/api?name=shubham and see the result as shown below.

Open the browser and enter
Facebooktwitterredditpinterestlinkedinmailby feather