WEB API Tutorial
WEB API
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
- Supports convention-based CRUD actions, since it works with HTTP verbs GET, POST, PUT and DELETE.
GET (Read)
Retrieves the representation of the resource.
PUT(Update)
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
- ASP.NET MVC 4
- VS 2010
Web API 2.0
- .NET Framework 4.5
- ASP.NET MVC 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. |
Create a Web API project
There are two ways to create a Web API project.
- Web API with MVC Project.
- 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.
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.
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.
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
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.
- 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.
- 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.
- 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.
These web packages are Displayed After Installation of WEB API Packages.
- 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.
- 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
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace HelloWebAPI.Configuration { public static class HelloWebAPIConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
- 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.
- 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.
Global.asax: public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configure(HelloWebAPIConfig.Register); } }
- Now, let's add Web API controller by right clicking on the Controllers folder and select Controller. this will open popup as below.
- 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.
- It will create a following empty HelloController class in Controllers Directory.
Example: Web API Controller
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace HelloWebAPI.Controller { public class HelloController : ApiController { } }
- Now, we need to add action methods.
Example: Web API Controller
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace HelloWebAPI.Controller { public class HelloController : ApiController { public string Get() { return "Hello World"; } } }
- Now, compile and run the Project and drive to "http://localhost:xxxx/api/hello" in the browser.
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
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MyWeb.Controllers { public class ValuesController : ApiController { // GET:- api/employee public IEnumerable<string> Get() { return new string[] { "v1", "v2" }; } // GET:- api/employee/5 public string Get(int id) { return "value"; } // POST:- api/employee public void Post([FromBody]string value) { } // PUT:- api/employee/5 public void Put(int id, [FromBody]string value) { } // DELETE:- api/employee/5 public void Delete(int id) { } } }
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 Characteristics
- It must be obtained from the System.Web.Http.ApiController class.
- 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.
- The name of the Action method can be the same as the HTTP verb name.
- 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:-
Get()
get()
GET()
GetAllEmployee()
Usage:- It uses for Retrieves the Data.
2.HTTP Method:-POST
Possible Web API Action Method Name:-
Post()
post()
POST()
PostNewEmployee()
Usage:-It uses forInserts new record.
3.HTTP Method:-PUT
Possible Web API Action Method Name:-
Put()
put()
PUT()
PutEmployee()
Usage:-It uses forUpdates existing record.
4.HTTP Method:-PATCH
Possible Web API Action Method Name:-
Patch()
patch()
PATCH()
PatchEmployee()
Usage:-It uses forUpdates record partially.
5.HTTP Method:-DELETE
Possible Web API Action Method Name:-
Delete()
delete()
DELETE()
DeleteEmployee()
Usage:-It is used toDelete the Records.
Difference between Web API and MVC controller
- Web API Controllers Receives from System.Web.Http.ApiController class, but MVC Controller Receives from System.Web.Mvc.Controller class.
- 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.
- 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.
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
- DependencyResolver:- Gets or sets the province(dependency) resolver for province injection.
- Filters:-Gets or sets the filters.
- Formatters:- Gets or sets the media-type formatters.
- IncludeErrorDetailPolicy :- Its Valueindicate whether error details should be entered in error message or not.
- MessageHandlers:-Gets or sets the message handlers.
- ParameterBindingRules:-Gets the collection of rules for how parameters should be bound.
- Services:- Gets the Web API services.
Web API Routing
Web API Rout two types of routing:
- Convention-based Routing.
- 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
public static class Config { public static void Reg(HttpConfiguration config) { // Enable attribute routing config.MapHttpAttributeRoutes(); // Add default route using convention-based routing config.Routes.MapHttpRoute( name: "DefaultName", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
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
public static class WebConfig { public static void Reg(HttpConfiguration config) { config.MapHttpAttributeRoutes(); // define route IHttpRoute defaultRoute = config.Routes.CreateRoute("api/{controller}/{id}", new { id = RouteParameter.Optional }, null); // Add route config.Routes.Add("DefaultWebApi", defaultRoute); } }
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.
- Void
- primitive type or Complex type
- HttpResponseMessage
- IHttpActionResult
VOID
Void is a Function that does not return any value after the function execution.
Example: Void Return Type:-
public class EmployeeController : ApiController { public void Delete(int id) { DeleteEmployeeFromDB(id); } }
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:-
public class Employee { public int Id { get; set; } public string Name { get; set; } } public class EmployeeController : ApiController { public int GetId(string name) { int id = GetEmployeeId(name); return id; } public Employee GetEmployee(int id) { var employee = GetEmployeeFromDB(id); return employee; } }
HttpResponseMessage
Web API controller always delivers an object of HttpResponseMessage to the hosting infrastructure. The following design illustrates the overall Web API request/response pipeline.
Example: Return HttpResponseMessage
public HttpResponseMessage Get(int id) { Employee emp = GetEmployeeFromDB(id); if (emp == null) { return Request.CreateResponse(HttpStatusCode.NotFound, id); } return Request.CreateResponse(HttpStatusCode.OK, emp); }
IHttpActionResult
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
public IHttpActionResult Get(int id) { Employee stud = GetEmployeeFromDB(id); if (stud == null) { return NotFound(); } return Ok(stud); }
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:
GET http://localhost:65684/api/Employee HTTP/1.1 User-Agent: Shubham Host: localhost:1234 Accept: application/json
- HTTP POST Request:
POST http://localhost:65684/api/Employee?age=21 HTTP/1.1 User-Agent: Shubham Host: localhost:65684 Content-Type: application/json Content-Length: 14 { id:7, name:'Shubham Wadwa' }
Example: Post Action Method
public class Employee { public int Id{ get; set; } public string Name{ get; set; } public string Address{ get; set; } } public class EmployeeController : ApiController { public Employee Post(Employee employee) { // save employee into db var insertedEmployee = SaveEmployee(employee); return insertedEmployee; } }
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
[Log] public class EmployeeController : ApiController { public EmployeeController() { } public Employee Get() { //provide implementation } }
HttpClient
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
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MyWebAPI.Controller { public class EmployeeController : ApiController { public IHttpActionResult GetAllEmployee(bool includeAddress = false) { IList<EmployeeViewModel> employees = null; using (var ctx = new CompanyDBEntities()) { Employees = ctx.Employees.Include("EmployeeAddress").Select(s => new EmployeeViewModel() { Id = s.EmployeeID, FirstName = s.FirstName, LastName = s.LastName, Address = s.EmployeeAddress == null || includeAddress == false ? null : new AddressViewModel() { EmployeeId = s.EmployeeAddress.EmployeeID, Address1 = s.EmployeeAddress.Address1, Address2 = s.EmployeeAddress.Address2, City = s.EmployeeAddress.City, State = s.EmployeeAddress.State } }).ToList<EmployeeViewModel>(); } if (Employee.Count == 0) { return NotFound(); } return Ok(Employees); } public IHttpActionResult PostNewEmployee(EmployeeViewModel Employee) { if (!ModelState.IsValid) return BadRequest("Not a valid data"); using (var ctx = new EmployeeDBEntities()) { ctx.Employees.Add(new Employee() { EmployeeID = Employee.Id, FirstName = Employee.FirstName, LastName = Employee.LastName }); ctx.SaveChanges(); } return Ok(); } public IHttpActionResult Put(EmployeeViewModel employee) { if (!ModelState.IsValid) return BadRequest("Not a valid data"); using (var ctx = new CompanyDBEntities()) { var existingEmployee = ctx.Employees.Where(s => s.EmployeeID == Employee.Id).FirstOrDefault<Employee>(); if (existingEmployee != null) { existingEmployee.FirstName = Employee.FirstName; existingEmployee.LastName = Employee.LastName; ctx.SaveChanges(); } else { return NotFound(); } } return Ok(); } public IHttpActionResult Delete(int id) { if (id <= 0) return BadRequest("Not a valid studet id"); using (var ctx = new CompanyDBEntities()) { var Employee = ctx.Employees .Where(s => s.EmployeeID == id) .FirstOrDefault(); ctx.Entry(employee).State = System.Data.Entity.EntityState.Deleted; ctx.SaveChanges(); } return Ok(); } } }
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
public class Employee { public int Id { get; set; } public string Name { get; set; } }
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
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; namespace HttpClientDemo { class Program { static void Main(string[] args) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:65648/api/"); //HTTP GET var responseTask = client.GetAsync("student"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<Student[]>(); readTask.Wait(); var employees = readTask.Result; foreach (var employee in employees) { Console.WriteLine(student.Name); } } } Console.ReadLine(); } } }
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
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.
- HttpConfiguration is used to configure a Web API
- 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.
Step 2:- 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.
Click on Accept Button in the License Acceptance window.
This will install the package into your project.
Now write the following code in the Main() method of Program class.
Example:- Self-Hosting Web API
class Program { static void Main(string[] args) { var config = new HttpSelfHostConfiguration("http://localhost:1447"); var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler()); var task = server.OpenAsync(); task.Wait(); Console.WriteLine("Web API Server has started at http://localhost:1447"); Console.ReadLine(); } }
Create My WebAPIMessageHandler class and write the following code.
Example: MessageHandler
classMyWebAPIMessageHandler
:
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; } }
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.
Open web browser and enter http://localhost:1447/ and see the result.
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
publicclass
HomeController
: ApiController { public string Get() { return "Hello World!"; } public string Get(string name) { return "Hello " + name; } }
Now, in the Main() method, configure a default route using config object as shown below.
Example: Self Hosting Web API
static void Main(string[] args) { var config = new HttpSelfHostConfiguration("http://localhost:1447"); config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { controller = "Home", id = RouteParameter.Optional }); var server = new HttpSelfHostServer(config); var task = server.OpenAsync(); task.Wait(); Console.WriteLine("Web API Server has started at http://localhost:1447"); Console.ReadLine(); }
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.