{"id":1816,"date":"2023-06-14T12:26:57","date_gmt":"2023-06-14T12:26:57","guid":{"rendered":"http:\/\/waqar-arshad.com\/?p=1816"},"modified":"2023-08-01T06:40:47","modified_gmt":"2023-08-01T06:40:47","slug":"asp-net-web-api","status":"publish","type":"post","link":"http:\/\/waqar-arshad.com\/index.php\/2023\/06\/14\/asp-net-web-api\/","title":{"rendered":"Asp.Net Web API with 50 Plus Interview Questions"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1816\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">1    <\/span>\r\n<\/div><div class=\"pld-dislike-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-dislike-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1816\" data-trigger-type=\"dislike\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-down\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-dislike-count-wrap pld-count-wrap\"><\/span>\r\n<\/div><\/div>\n<p><strong>What is Web API?<\/strong><\/p>\n\n\n\n<p>Before we understand what is Web API, let&#8217;s see what is an API (Application Programing Interface).<\/p>\n\n\n\n<p>As per&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Application_programming_interface\" target=\"_blank\" rel=\"noreferrer noopener\">Wikipedia&#8217;s Definition of API<\/a>: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications.<\/p>\n\n\n\n<p>To put it in simple terms, API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.<\/p>\n\n\n\n<p>Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol. It is a concept and not a technology. We can build Web API using different technologies such as Java, .NET etc. For example, Twitter&#8217;s&nbsp;<a href=\"https:\/\/dev.twitter.com\/rest\/public\" target=\"_blank\" rel=\"noreferrer noopener\">REST APIs<\/a>&nbsp;provide programmatic access to read and write data using which we can integrate twitter&#8217;s capabilities into our own application.<\/p>\n\n\n\n<p><strong>ASP.NET Web API<\/strong><\/p>\n\n\n\n<p>The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view. It is like a webservice or WCF service but the exception is that it only supports HTTP protocol.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1013\" height=\"527\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image.png\" alt=\"\" class=\"wp-image-2150\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image.png 1013w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-300x156.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-768x400.png 768w\" sizes=\"auto, (max-width: 1013px) 100vw, 1013px\" \/><\/figure>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-overview.png\" target=\"_blank\"><\/a><\/p>\n\n\n\n<p><strong>ASP.NET Web API Characteristics<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>ASP.NET Web API is an ideal platform for building RESTful services.<\/li>\n\n\n\n<li>ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request\/response pipeline<\/li>\n\n\n\n<li>ASP.NET Web API maps HTTP verbs to method names.<\/li>\n\n\n\n<li>ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.<\/li>\n\n\n\n<li>ASP.NET Web API can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.<\/li>\n\n\n\n<li>ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.<\/li>\n<\/ol>\n\n\n\n<p>ASP.NET Web API Versions<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Web API Version<\/td><td>Supported .NET Framework<\/td><td>Coincides with<\/td><td>Supported in<\/td><\/tr><\/thead><tbody><tr><td>Web API 1.0<\/td><td>.NET Framework 4.0<\/td><td>ASP.NET MVC 4<\/td><td>VS 2010<\/td><\/tr><tr><td>Web API 2 &#8211; Current<\/td><td>.NET Framework 4.5<\/td><td>ASP.NET MVC 5<\/td><td>VS 2012, 2013<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>ASP.NET Web API vs WCF<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Web API<\/td><td>WCF<\/td><\/tr><\/thead><tbody><tr><td>Open source and ships with .NET framework.<\/td><td>Ships with .NET framework<\/td><\/tr><tr><td>Supports only HTTP protocol.<\/td><td>Supports HTTP, TCP, UDP and custom transport protocol.<\/td><\/tr><tr><td>Maps http verbs to methods<\/td><td>Uses attributes based programming model.<\/td><\/tr><tr><td>Uses routing and controller concept similar to ASP.NET MVC.<\/td><td>Uses Service, Operation and Data contracts.<\/td><\/tr><tr><td>Does not support Reliable Messaging and transaction.<\/td><td>Supports Reliable Messaging and Transactions.<\/td><\/tr><tr><td>Web API can be configured using HttpConfiguration class but not in web.config.<\/td><td>Uses web.config and attributes to configure a service.<\/td><\/tr><tr><td>Ideal for building RESTful services.<\/td><td>Supports RESTful services but with limitations.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>When to choose WCF?<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Choose WCF if you use .NET Framework 3.5. Web API does not support .NET 3.5 or below.<\/li>\n\n\n\n<li>Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named pipe.<\/li>\n\n\n\n<li>Choose WCF if you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security.<\/li>\n\n\n\n<li>Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange patterns.<\/li>\n<\/ul>\n\n\n\n<p>When to choose ASP.NET Web API?<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Choose Web API if you are using .NET framework 4.0 or above.<\/li>\n\n\n\n<li>Choose Web API if you want to build a service that supports only HTTP protocol.<\/li>\n\n\n\n<li>Choose Web API to build RESTful HTTP based services.<\/li>\n\n\n\n<li>Choose Web API if you are familiar with ASP.NET MVC.<\/li>\n<\/ul>\n\n\n\n<p>Web API Controllers<\/p>\n\n\n\n<p>We created Web API with MVC project in the previous section where it generated a simple controller. Here, you will learn about Web API Controller in detail.<\/p>\n\n\n\n<p>Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.<\/p>\n\n\n\n<p>Web API controller is a class which can be created under the&nbsp;<strong>Controllers<\/strong>&nbsp;folder or any other folder under your project&#8217;s root folder. The name of a controller class must end with &#8220;Controller&#8221; and it must be derived from System.Web.Http.<strong>ApiController<\/strong>&nbsp;class. All the public methods of the controller are called action methods.<\/p>\n\n\n\n<p>The following is a simple controller class added by visual studio by default when we created a new Web API project in the&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/webapi\/create-web-api-project\">Create Web API Project<\/a>&nbsp;section.<\/p>\n\n\n\n<p>Example: Simple Web API Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>using System;<\/p>\n\n\n\n<p>using System.Collections.Generic;<\/p>\n\n\n\n<p>using System.Linq;<\/p>\n\n\n\n<p>using System.Net;<\/p>\n\n\n\n<p>using System.Net.Http;<\/p>\n\n\n\n<p>using System.Web.Http;<\/p>\n\n\n\n<p>namespace MyWebAPI.Controllers<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public class ValuesController : ApiController<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ GET: api\/values<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IEnumerable&lt;string&gt; Get()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new string[] { &#8220;value1&#8221;, &#8220;value2&#8221; };<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ GET: api\/values\/5<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Get(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;value&#8221;;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ POST: api\/values<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Post([FromBody]string value)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ PUT: api\/values\/5<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Put(int id, [FromBody]string value)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ DELETE: api\/values\/5<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Delete(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As you can see in the above example, ValuesController class is derived from ApiController and includes multiple action methods whose names match with HTTP verbs like Get, Post, Put and Delete.<\/p>\n\n\n\n<p>Based on the incoming request URL and HTTP verb (GET\/POST\/PUT\/PATCH\/DELETE), Web API decides which Web API controller and action method to execute e.g. Get() method will handle HTTP GET request, Post() method will handle HTTP POST request, Put() mehtod will handle HTTP PUT request and Delete() method will handle HTTP DELETE request for the above Web API.<\/p>\n\n\n\n<p>The following figure illustrates the significance of Web API controller and action methods.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-controller.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Web API Controller Overview<\/p>\n\n\n\n<p>If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.<\/p>\n\n\n\n<p>Example: Simple Web API Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>using System;<\/p>\n\n\n\n<p>using System.Collections.Generic;<\/p>\n\n\n\n<p>using System.Linq;<\/p>\n\n\n\n<p>using System.Net;<\/p>\n\n\n\n<p>using System.Net.Http;<\/p>\n\n\n\n<p>using System.Web.Http;<\/p>\n\n\n\n<p>namespace MyWebAPI.Controllers<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public class ValuesController : ApiController<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HttpGet]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IEnumerable&lt;string&gt; Values()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new string[] { &#8220;value1&#8221;, &#8220;value2&#8221; };<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HttpGet]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Value(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;value&#8221;;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HttpPost]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void SaveNewValue([FromBody]string value)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HttpPut]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void UpdateValue(int id, [FromBody]string value)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HttpDelete]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void RemoveValue(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Web API Controller Characteristics<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>It must be derived from&nbsp;System.Web.Http.ApiController&nbsp;class.<\/li>\n\n\n\n<li>It can be created under any folder in the project&#8217;s root folder. However, it is recommended to create controller classes in the&nbsp;<strong>Controllers<\/strong>&nbsp;folder as per the convention.<\/li>\n\n\n\n<li>Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method.<\/li>\n\n\n\n<li>Return type of an action method can be any primitive or complex type. Learn more about it&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/webapi\/request-response-data-formats-in-web-api\">here<\/a>.<\/li>\n<\/ol>\n\n\n\n<p>Action Method Naming Conventions<\/p>\n\n\n\n<p>As mentioned above, name of the action methods in the Web API controller plays an important role. Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above. However, you can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllNames(), GetStudents() or any other name which starts with Get.<\/p>\n\n\n\n<p>The following table lists possible action method names for each HTTP method:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>HTTP Method<\/td><td>Possible Web API Action Method Name<\/td><td>Usage<\/td><\/tr><\/thead><tbody><tr><td>GET<\/td><td>Get()<br>get()<br>GET()<br>GetAllStudent()<br>*any name starting with Get *<\/td><td>Retrieves data.<\/td><\/tr><tr><td>POST<\/td><td>Post()<br>post()<br>POST()<br>PostNewStudent()<br>*any name starting with Post*<\/td><td>Inserts new record.<\/td><\/tr><tr><td>PUT<\/td><td>Put()<br>put()<br>PUT()<br>PutStudent()<br>*any name starting with Put*<\/td><td>Updates existing record.<\/td><\/tr><tr><td>PATCH<\/td><td>Patch()<br>patch()<br>PATCH()<br>PatchStudent()<br>*any name starting with Patch*<\/td><td>Updates record partially.<\/td><\/tr><tr><td>DELETE<\/td><td>Delete()<br>delete()<br>DELETE()<br>DeleteStudent()<br>*any name starting with Delete*<\/td><td>Deletes record.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The following figure illustrates the overall request\/response pipeline.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-request-pipeline.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Web API Request Pipeline<\/p>\n\n\n\n<p>Visit&nbsp;<a href=\"https:\/\/www.asp.net\/media\/4071077\/aspnet-web-api-poster.pdf\" target=\"_blank\" rel=\"noreferrer noopener\">Web API HTTP Message Life Cycle Poster<\/a>&nbsp;for more details.<\/p>\n\n\n\n<p><strong>Difference between Web API and MVC controller<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Web API Controller<\/td><td>MVC Controller<\/td><\/tr><\/thead><tbody><tr><td>Derives from System.Web.Http.ApiController class<\/td><td>Derives from System.Web.Mvc.Controller class.<\/td><\/tr><tr><td>Method name must start with Http verbs otherwise apply http verbs attribute.<\/td><td>Must apply appropriate Http verbs attribute.<\/td><\/tr><tr><td>Specialized in returning data.<\/td><td>Specialized in rendering view.<\/td><\/tr><tr><td>Return data automatically formatted based on Accept-Type header attribute. Default to json or xml.<\/td><td>Returns ActionResult or any derived type.<\/td><\/tr><tr><td>Requires .NET 4.0 or above<\/td><td>Requires .NET 3.5 or above<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\"><br><br><\/figcaption><\/figure>\n\n\n\n<h1 class=\"wp-block-heading\">Configure Web API<\/h1>\n\n\n\n<p>Web API supports code based configuration. It cannot be configured in web.config file. We can configure Web API to customize the behaviour of Web API hosting infrastructure and components such as routes, formatters, filters, DependencyResolver, MessageHandlers, ParamterBindingRules, properties, services etc.<\/p>\n\n\n\n<p>We created a simple Web API project in the&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/webapi\/create-web-api-project\">Create Web API Project<\/a>&nbsp;section. Web API project includes default WebApiConfig class in the App_Start folder and also includes Global.asax as shown below.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapiconfig.png\" target=\"_blank\"><\/a>Configure Web API<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"438\" height=\"833\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-1.png\" alt=\"\" class=\"wp-image-1820\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-1.png 438w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-1-158x300.png 158w\" sizes=\"auto, (max-width: 438px) 100vw, 438px\" \/><\/figure>\n\n\n\n<p>Global.asax<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>WebAPIApplication<code> : System.Web.<\/code>HttpApplication<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>protected<code> <\/code>void<code> Application_Start()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>GlobalConfiguration<code>.Configure(<\/code>WebApiConfig<code>.Register);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code>\/\/other configuration<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>WebApiConfig<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>static<code> <\/code>class<code> <\/code>WebApiConfig<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>static<code> <\/code>void<code> Register(<\/code>HttpConfiguration<code> config)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: <\/code>\"DefaultApi\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: <\/code>\"api\/{controller}\/{id}\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: <\/code>new<code> { id = RouteParameter.Optional }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/ configure additional webapi settings here..<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>Web API configuration process starts when the application starts. It calls&nbsp;<code>GlobalConfiguration.Configure(WebApiConfig.Register)<\/code>&nbsp;in the Application_Start method. The Configure() method requires the callback method where Web API has been configured in code. By default this is the static WebApiConfig.Register() method.<\/p>\n\n\n\n<p>As you can see above,&nbsp;<code>WebApiConfig.Register()<\/code>&nbsp;method includes a parameter of&nbsp;<code>HttpConfiguration<\/code>&nbsp;type which is then used to configure the Web API. The&nbsp;<code>HttpConfiguration<\/code>&nbsp;is the main class which includes following properties using which you can override the default behaviour of Web API.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Property<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>DependencyResolver<\/td><td>Gets or sets the dependency resolver for dependency injection.<\/td><\/tr><tr><td>Filters<\/td><td>Gets or sets the filters.<\/td><\/tr><tr><td>Formatters<\/td><td>Gets or sets the media-type formatters.<\/td><\/tr><tr><td>IncludeErrorDetailPolicy<\/td><td>Gets or sets a value indicating whether error details should be included in error messages.<\/td><\/tr><tr><td>MessageHandlers<\/td><td>Gets or sets the message handlers.<\/td><\/tr><tr><td>ParameterBindingRules<\/td><td>Gets the collection of rules for how parameters should be bound.<\/td><\/tr><tr><td>Properties<\/td><td>Gets the properties associated with this Web API instance.<\/td><\/tr><tr><td>Routes<\/td><td>Gets the collection of routes configured for the Web API.<\/td><\/tr><tr><td>Services<\/td><td>Gets the Web API services.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Web API Routing<\/p>\n\n\n\n<p>In the previous section, we learned that Web API can be configured in WebApiConfig class. Here, we will learn how to configure Web API routes.<\/p>\n\n\n\n<p>Web API routing is similar to&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/mvc\/routing-in-mvc\">ASP.NET MVC Routing<\/a>. It routes an incoming HTTP request to a particular action method on a Web API controller.<\/p>\n\n\n\n<p>Web API supports two types of routing:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>Convention-based Routing<\/li>\n\n\n\n<li>Attribute Routing<\/li>\n<\/ol>\n\n\n\n<p>Convention-based Routing<\/p>\n\n\n\n<p>In the 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 into route table in order to handle various HTTP requests.<\/p>\n\n\n\n<p>When we created Web API project using WebAPI template in the&nbsp;<a href=\"https:\/\/www.tutorialsteacher.com\/webapi\/create-web-api-project\">Create Web API Project<\/a>&nbsp;section, it also added WebApiConfig class in the App_Start folder with default route as shown below.<\/p>\n\n\n\n<p>Example: WebApiConfig with Default Route<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public static class WebApiConfig<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public static void Register(HttpConfiguration config)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ Enable attribute routing<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ Add default route using convention-based routing<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: &#8220;DefaultApi&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: &#8220;api\/{controller}\/{id}&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: new { id = RouteParameter.Optional }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the above WebApiConfig.Register() method,&nbsp;config.MapHttpAttributeRoutes()&nbsp;enables attribute routing which we will learn later in this section. The&nbsp;config.Routes&nbsp;is a route table or route collection of type&nbsp;<a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.web.http.httproutecollection(v=vs.118).aspx\" target=\"_blank\" rel=\"noreferrer noopener\">HttpRouteCollection<\/a>. The &#8220;DefaultApi&#8221; route is added in the route table using&nbsp;<a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh835153(v=vs.118).aspx\" target=\"_blank\" rel=\"noreferrer noopener\">MapHttpRoute()<\/a>&nbsp;extension method. The&nbsp;MapHttpRoute()&nbsp;extension method internally creates a new instance of&nbsp;<a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.web.http.routing.ihttproute(v=vs.118).aspx\" target=\"_blank\" rel=\"noreferrer noopener\">IHttpRoute<\/a>&nbsp;and adds it to an HttpRouteCollection. However, you can create a new route and add it into a collection manually as shown below.<\/p>\n\n\n\n<p>Example: Add Default Route<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public static class WebApiConfig<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public static void Register(HttpConfiguration config)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ define route<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IHttpRoute defaultRoute = config.Routes.CreateRoute(&#8220;api\/{controller}\/{id}&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new { id = RouteParameter.Optional }, null);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ Add route<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.Add(&#8220;DefaultApi&#8221;, defaultRoute);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>The following table lists parameters of MapHttpRoute() method.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Parameter<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>name<\/td><td>Name of the route<\/td><\/tr><tr><td>routeTemplate<\/td><td>URL pattern of the route<\/td><\/tr><tr><td>defaults<\/td><td>An object parameter that includes default route values<\/td><\/tr><tr><td>constraints<\/td><td>Regex expression to specify characteristic of route values<\/td><\/tr><tr><td>handler<\/td><td>The handler to which the request will be dispatched.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Now, let&#8217;s see how Web API handles an incoming http request and sends the response.<\/p>\n\n\n\n<p>The following is a sample HTTP GET request.<\/p>\n\n\n\n<p>Sample HTTP GET Request<\/p>\n\n\n\n<p>GET http:\/\/localhost:1234\/api\/values\/ HTTP\/1.1<\/p>\n\n\n\n<p>User-Agent: Fiddler<\/p>\n\n\n\n<p>Host: localhost: 60464<\/p>\n\n\n\n<p>Content-Type: application\/json<\/p>\n\n\n\n<p>Considering the DefaultApi route configured in the above WebApiConfig class, the above request will execute Get() action method of the ValuesController because HTTP method is a GET and URL is&nbsp;http:\/\/localhost:1234\/api\/values&nbsp;which matches with DefaultApi&#8217;s route template&nbsp;\/api\/{controller}\/{id}&nbsp;where value of {controller} will be ValuesController. Default route has specified id as an optional parameter so if an id is not present in the url then {id} will be ignored. The request&#8217;s HTTP method is GET so it will execute Get() action method of ValueController.<\/p>\n\n\n\n<p>If Web API framework does not find matched routes for an incoming request then it will send 404 error response.<\/p>\n\n\n\n<p>The following figure illustrates Web API Routing.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-routing.png\" target=\"_blank\"><\/a>Web API Routing<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1013\" height=\"616\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-1.png\" alt=\"\" class=\"wp-image-2152\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-1.png 1013w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-1-300x182.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-1-768x467.png 768w\" sizes=\"auto, (max-width: 1013px) 100vw, 1013px\" \/><\/figure>\n\n\n\n<p>The following table displays which action method and controller will be executed on different incoming requests.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Request URL<\/td><td>Request HTTP Method<\/td><td>Action method<\/td><td>Controller<\/td><\/tr><\/thead><tbody><tr><td>http:\/\/localhost:1234\/api\/course<\/td><td>GET<\/td><td>Get()<\/td><td>CourseController<\/td><\/tr><tr><td>http:\/\/localhost:1234\/api\/product<\/td><td>POST<\/td><td>Post()<\/td><td>ProductController<\/td><\/tr><tr><td>http:\/\/localhost:1234\/api\/teacher<\/td><td>PUT<\/td><td>Put()<\/td><td>TeacherController<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>&nbsp;Note:<\/p>\n\n\n\n<p>Web API also supports routing same as ASP.NET MVC by including action method name in the URL.<\/p>\n\n\n\n<p>Configure Multiple Routes<\/p>\n\n\n\n<p>We configured a single route above. However, you can configure multiple routes in the Web API using HttpConfiguration object. The following example demonstrates configuring multiple routes.<\/p>\n\n\n\n<p>Example: Multiple Routes<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public static class WebApiConfig<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public static void Register(HttpConfiguration config)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ school route<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: &#8220;School&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: &#8220;api\/myschool\/{id}&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: new { controller=&#8221;school&#8221;, id = RouteParameter.Optional }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; constraints: new { id =&#8221;\/d+&#8221; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ default route<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: &#8220;DefaultApi&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: &#8220;api\/{controller}\/{id}&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: new { id = RouteParameter.Optional }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the above example, School route is configured before DefaultApi route. So any incoming request will be matched with the School route first and if incoming request url does not match with it then only it will be matched with DefaultApi route. For example, request url is&nbsp;http:\/\/localhost:1234\/api\/myschool&nbsp;is matched with School route template, so it will be handled by SchoolController.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Parameter Binding in ASP.NET Web API<\/h1>\n\n\n\n<p>In the previous section, we learned how Web API route an HTTP request to a controller and action method. Here, we will learn how Web API binds HTTP request data to the parameters of an action method.<\/p>\n\n\n\n<p>Action methods in Web API controllers can have one or more parameters of different types. It can be either primitive type or complex type. Web API binds action method parameters with the URL&#8217;s query string or with the request body depending on the parameter type.<\/p>\n\n\n\n<p>By default, if the parameter type is of .NET primitive types such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from string type, then it sets the value of a parameter from the query string. And if the parameter type is the complex type, then Web API tries to get the value from the request body by default.<\/p>\n\n\n\n<p>The following table lists the default rules for parameter binding.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>HTTP Method<\/td><td>Query String<\/td><td>Request Body<\/td><\/tr><\/thead><tbody><tr><td>GET<\/td><td>Primitive Type,<br>Complex Type<\/td><td>NA<\/td><\/tr><tr><td>POST<\/td><td>Primitive Type<\/td><td>Complex Type<\/td><\/tr><tr><td>PUT<\/td><td>Primitive Type<\/td><td>Complex Type<\/td><\/tr><tr><td>PATCH<\/td><td>Primitive Type<\/td><td>Complex Type<\/td><\/tr><tr><td>DELETE<\/td><td>Primitive Type,<br>Complex Type<\/td><td>NA<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Let&#8217;s see how Web API get values of action method parameters from the HTTP request.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Get Action Method with Primitive Parameter<\/h2>\n\n\n\n<p>Consider the following example of the&nbsp;<code>GET<\/code>&nbsp;action method that includes a single primitive type parameter.<\/p>\n\n\n\n<p>Example: Primitive Parameter Binding<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Get(<\/code>int<code> id) <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>As you can see, the above HTTP&nbsp;<code>GET<\/code>&nbsp;action method includes the&nbsp;<code>id<\/code>&nbsp;parameter of the&nbsp;<code>int<\/code>&nbsp;type. So, Web API will try to extract the value of id from the query string of the requested URL, convert it into int and assign it to the&nbsp;<code>id<\/code>&nbsp;parameter of the&nbsp;<code>GET<\/code>&nbsp;action method. For example, if an HTTP request is&nbsp;<code>http:\/\/localhost\/api\/student?id=1<\/code>&nbsp;then the value of the&nbsp;<code>id<\/code>&nbsp;parameter will be 1.<\/p>\n\n\n\n<p>The followings are valid HTTP&nbsp;<code>GET<\/code>&nbsp;Requests for the above action method.<\/p>\n\n\n\n<p><code>http:\/\/localhost\/api\/student?id=1<\/code><\/p>\n\n\n\n<p><code>http:\/\/localhost\/api\/student?ID=1<\/code><\/p>\n\n\n\n<p>&nbsp;Note:<\/p>\n\n\n\n<p>Query string parameter name and action method parameter name must be the same (case-insensitive). If names do not match, then the values of the parameters will not be set. The order of the parameters can be different.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Multiple Primitive Parameters<\/h2>\n\n\n\n<p>Consider the following example of the&nbsp;<code>GET<\/code>&nbsp;action method with multiple primitive parameters.<\/p>\n\n\n\n<p>Example: Multiple Parameters Binding<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Get(<\/code>int<code> id, <\/code>string<code> name) <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>As you can see above, an HTTP&nbsp;<code>GET<\/code>&nbsp;method includes multiple primitive type parameters. So, Web API will try to extract the values from the query string of the requested URL. For example, if an HTTP request is&nbsp;<code>http:\/\/localhost\/api\/student?id=1&amp;name=steve<\/code>, then the value of the&nbsp;<code>id<\/code>&nbsp;parameter will be 1, and the&nbsp;<code>name<\/code>&nbsp;parameter will be&nbsp;<code>\"steve\"<\/code>.<\/p>\n\n\n\n<p>Followings are valid HTTP GET Requests for the above action method.<\/p>\n\n\n\n<p><code>http:\/\/localhost\/api\/student?id=1&amp;name=steve<\/code><\/p>\n\n\n\n<p><code>http:\/\/localhost\/api\/student?ID=1&amp;NAME=steve<\/code><\/p>\n\n\n\n<p><code>http:\/\/localhost\/api\/student?name=steve&amp;id=1<\/code><\/p>\n\n\n\n<p>&nbsp;Note:<\/p>\n\n\n\n<p>Query string parameter names must match with the name of an action method parameter. However, they can be in a different order.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">POST Action Method with Primitive Parameter<\/h2>\n\n\n\n<p>An HTTP&nbsp;<code>POST<\/code>&nbsp;request is used to create a new resource. It can include request data into the HTTP request body and also in the query string.<\/p>\n\n\n\n<p>Consider the following Post action method.<\/p>\n\n\n\n<p>Example: Post Method with Primitive Parameter<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Post(<\/code>id<code> id, <\/code>string<code> name)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>As you can see above, the&nbsp;<code>Post()<\/code>&nbsp;action method includes primitive type parameters id and name. So, by default, Web API will get values from the query string. For example, if an HTTP POST request is&nbsp;<code>http:\/\/localhost\/api\/student?id=1&amp;name=steve<\/code>, then the value of the&nbsp;<code>id<\/code>&nbsp;parameter will be 1 and the&nbsp;<code>name<\/code>&nbsp;parameter will be&nbsp;<code>\"steve\"<\/code>&nbsp;in the above&nbsp;<code>Post()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>Now, consider the following&nbsp;<code>Post()<\/code>&nbsp;method with the complex type parameter.<\/p>\n\n\n\n<p>Example: Post Method with Complex Type Parameter<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>Student<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>int<code> Id { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>string<code> Name { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Post(<\/code>Student<code> stud)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above&nbsp;<code>Post()<\/code>&nbsp;method includes the&nbsp;<code>Student<\/code>&nbsp;type parameter. So, as a default rule, Web API will try to get the values of the&nbsp;<code>stud<\/code>&nbsp;parameter from the HTTP request body.<\/p>\n\n\n\n<p>Following is a valid HTTP POST request in the fiddler for the above action method.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/fiddler-example1.png\" target=\"_blank\"><\/a>Parameter Binding<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"466\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-3.png\" alt=\"\" class=\"wp-image-1822\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-3.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-3-300x149.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-3-768x381.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>Web API will extract the JSON object from the HTTP request body above, and convert it into a&nbsp;<code>Student<\/code>&nbsp;object automatically because the names of JSON object&#8217;s properties match with the name of the&nbsp;<code>Student<\/code>&nbsp;class properties (case-insensitive).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">POST Method with Mixed Parameters<\/h2>\n\n\n\n<p>The HTTP&nbsp;<code>Post<\/code>&nbsp;action methods can include primitive and complex type parameters. Consider the following example.<\/p>\n\n\n\n<p>Example: Post Method with Primitive and Complex Type Parameters<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>Student<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>int<code> Id { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>string<code> Name { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Post(<\/code>int<code> age, <\/code>Student<code> student)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above Post method includes both primitive and complex type parameters. So, by default , Web API will get the&nbsp;<code>age<\/code>&nbsp;parameter from query string and&nbsp;<code>student<\/code>&nbsp;parameter from the request body.<\/p>\n\n\n\n<p>Following is a valid HTTP POST request in the fiddler for the above action method.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/post-request-fiddler.png\" target=\"_blank\"><\/a>Parameter Binding<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"295\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-4.png\" alt=\"\" class=\"wp-image-1823\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-4.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-4-300x94.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-4-768x241.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>&nbsp;Note:<\/p>\n\n\n\n<p>Post action method cannot include multiple complex type parameters because, at most, one parameter is allowed to be read from the request body.<\/p>\n\n\n\n<p>Parameter binding for Put and Patch method will be the same as the&nbsp;<code>POST<\/code>&nbsp;method in Web API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">[FromUri] and [FromBody]<\/h2>\n\n\n\n<p>You have seen that by default, ASP.NET Web API gets the value of a primitive parameter from the query string and a complex type parameter from the request body. But, what if we want to change this default behavior?<\/p>\n\n\n\n<p>Use&nbsp;<code>[FromUri]<\/code>&nbsp;attribute to force Web API to get the value of complex type from the query string and&nbsp;<code>[FromBody]<\/code>&nbsp;attribute to get the value of primitive type from the request body, opposite to the default rules.<\/p>\n\n\n\n<p>For example, consider the following&nbsp;<code>GET<\/code>&nbsp;method.<\/p>\n\n\n\n<p>Example: FormUri<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Get([<\/code>FromUri<code>] <\/code>Student<code> stud)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>In the above example, the&nbsp;<code>Get()<\/code>&nbsp;method includes a complex type parameter with the&nbsp;<code>[FromUri]<\/code>&nbsp;attribute. So, Web API will try to get the value of the&nbsp;<code>Student<\/code>&nbsp;type parameter from the query string. For example, if an HTTP GET request&nbsp;<code>http:\/\/localhost:xxxx\/api\/student?id=1&amp;name=steve<\/code>&nbsp;then Web API will create an object the&nbsp;<code>Student<\/code>&nbsp;type and set its&nbsp;<code>id<\/code>&nbsp;and&nbsp;<code>name<\/code>&nbsp;property values to the value of&nbsp;<code>id<\/code>&nbsp;and&nbsp;<code>name<\/code>&nbsp;query string parameter.<\/p>\n\n\n\n<p>&nbsp;Note:<\/p>\n\n\n\n<p>The name of the complex type&#8217;s properties and the query string parameters must match.<\/p>\n\n\n\n<p>Action Method Return Type<\/p>\n\n\n\n<p>In the previous section, you learned about parameter binding with Web API action method. Here, you will learn about the return types of action methods which in turn will be embedded in the Web API response sent to the client.<\/p>\n\n\n\n<p>The Web API action method can have following return types.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>Void<\/li>\n\n\n\n<li>Primitive type or Complex type<\/li>\n\n\n\n<li>HttpResponseMessage<\/li>\n\n\n\n<li>IHttpActionResult<\/li>\n<\/ol>\n\n\n\n<p>Void<\/p>\n\n\n\n<p>It&#8217;s not necessary that all action methods must return something. It can have void return type.<\/p>\n\n\n\n<p>For example, consider the following Delete action method that just deletes the student from the data source and returns nothing.<\/p>\n\n\n\n<p>Example: Void Return Type<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class StudentController : ApiController<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public void Delete(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DeleteStudentFromDB(id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As you can see above Delete action method returns void. It will send 204 &#8220;No Content&#8221; status code as a response when you send HTTP DELETE request as shown below.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/void-response-status.png\" target=\"_blank\"><\/a>Void Response Status<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"158\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-5.png\" alt=\"\" class=\"wp-image-1824\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-5.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-5-300x50.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-5-768x129.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>Primitive or Complex Type<\/p>\n\n\n\n<p>An action method can return primitive or other custom complex types as other normal methods.<\/p>\n\n\n\n<p>Consider the following Get action methods.<\/p>\n\n\n\n<p>Example: Primitive or Complex Return Type<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class Student<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public int Id { get; set; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public string Name { get; set; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>public class StudentController : ApiController<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public int GetId(string name)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int id = GetStudentId(name);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return id;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public Student GetStudent(int id)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var student = GetStudentFromDB(id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return student;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As you can see above, GetId action method returns an integer and GetStudent action method returns a&nbsp;Student&nbsp;type.<\/p>\n\n\n\n<p>An HTTP GET request&nbsp;http:\/\/localhost:xxxx\/api\/student?name=john&nbsp;will return following response in Fiddler.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/primitive-return-type-response.png\" target=\"_blank\"><\/a>Primitive Return Type in Response<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"460\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-6.png\" alt=\"\" class=\"wp-image-1825\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-6.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-6-300x147.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-6-768x376.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>An HTTP GET request&nbsp;http:\/\/localhost:xxxx\/api\/student?id=1&nbsp;will return following response in Fiddler.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/primitive-return-type-response2.png\" target=\"_blank\"><\/a>Complex Return Type in Response<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"458\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-7.png\" alt=\"\" class=\"wp-image-1826\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-7.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-7-300x146.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-7-768x374.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>HttpResponseMessage<\/p>\n\n\n\n<p>Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API request\/response pipeline.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-request-pipeline.png\" target=\"_blank\"><\/a>Web API Request Pipeline<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-2.png\" alt=\"\" class=\"wp-image-2153\" width=\"705\" height=\"366\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-2.png 1013w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-2-300x156.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-2-768x400.png 768w\" sizes=\"auto, (max-width: 705px) 100vw, 705px\" \/><\/figure>\n\n\n\n<p>Visit&nbsp;<a href=\"https:\/\/www.asp.net\/media\/4071077\/aspnet-web-api-poster.pdf\" target=\"_blank\" rel=\"noreferrer noopener\">Web API HTTP Message Life Cycle Poster<\/a>&nbsp;for more details.<\/p>\n\n\n\n<p>As you can see in the above figure, the Web API controller returns HttpResponseMessage object. You can also create and return an object of HttpResponseMessage directly from an action method.<\/p>\n\n\n\n<p>The advantage of sending HttpResponseMessage from an action method is that you can configure a response your way. You can set the status code, content or error message (if any) as per your requirement.<\/p>\n\n\n\n<p>Example: Return HttpResponseMessage<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public HttpResponseMessage Get(int id)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; Student stud = GetStudentFromDB(id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; if (stud == null) {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Request.CreateResponse(HttpStatusCode.NotFound, id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return Request.CreateResponse(HttpStatusCode.OK, stud);<\/p>\n\n\n\n<p>}&nbsp;<\/p>\n\n\n\n<p>In the above action method, if there is no student with specified id in the DB then it will return HTTP 404 Not Found status code, otherwise it will return 200 OK status with student data.<\/p>\n\n\n\n<p>For example, an http GET request&nbsp;http:\/\/localhost:xxxx\/api\/student?id=100&nbsp;will get following response considering student with id=100 does not exists in the DB.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/httpresponsemessage1.png\" target=\"_blank\"><\/a>Web API Response in Fiddler<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"448\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-9.png\" alt=\"\" class=\"wp-image-1828\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-9.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-9-300x143.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-9-768x366.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>The same way, an HTTP GET request&nbsp;http:\/\/localhost:60464\/api\/student?id=1&nbsp;will get following response considering student with id=1 exists in the database .<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/httpresponsemessage2.png\" target=\"_blank\"><\/a>Web API Response in Fiddler<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"457\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-10.png\" alt=\"\" class=\"wp-image-1829\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-10.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-10-300x146.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-10-768x373.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>IHttpActionResult<\/p>\n\n\n\n<p>The&nbsp;<em>IHttpActionResult<\/em>&nbsp;was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.<\/p>\n\n\n\n<p>You can create your own class that implements IHttpActionResult or use various methods of&nbsp;ApiController&nbsp;class that returns an object that implement the IHttpActionResult.<\/p>\n\n\n\n<p>Example: Return IHttpActionResult Type using Ok() and NotFound() Methods<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public IHttpActionResult Get(int id)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; Student stud = GetStudentFromDB(id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; if (stud == null)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return NotFound();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return Ok(stud);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the above example, if student with specified id does not exists in the database then it will return response with the status code 404 otherwise it sends student data with status code 200 as a response. As you can see, we don&#8217;t have to write much code because NotFound() and Ok() method does it all for us.<\/p>\n\n\n\n<p>The following table lists all the methods of&nbsp;ApiController&nbsp;class that returns an object of a class that implements IHttpActionResult interface.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td><strong>ApiController&nbsp;Method<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><\/thead><tbody><tr><td>BadRequest()<\/td><td>Creates a BadRequestResult object with status code 400.<\/td><\/tr><tr><td>Conflict()<\/td><td>Creates a ConflictResult object with status code 409.<\/td><\/tr><tr><td>Content()<\/td><td>Creates a NegotiatedContentResult with the specified status code and data.<\/td><\/tr><tr><td>Created()<\/td><td>Creates a CreatedNegotiatedContentResult with status code 201 Created.<\/td><\/tr><tr><td>CreatedAtRoute()<\/td><td>Creates a CreatedAtRouteNegotiatedContentResult with status code 201 created.<\/td><\/tr><tr><td>InternalServerError()<\/td><td>Creates an InternalServerErrorResult with status code 500 Internal server error.<\/td><\/tr><tr><td>NotFound()<\/td><td>Creates a NotFoundResult with status code404.<\/td><\/tr><tr><td>Ok()<\/td><td>Creates an OkResult with status code 200.<\/td><\/tr><tr><td>Redirect()<\/td><td>Creates a RedirectResult with status code 302.<\/td><\/tr><tr><td>RedirectToRoute()<\/td><td>Creates a RedirectToRouteResult with status code 302.<\/td><\/tr><tr><td>ResponseMessage()<\/td><td>Creates a ResponseMessageResult with the specified HttpResponseMessage.<\/td><\/tr><tr><td>StatusCode()<\/td><td>Creates a StatusCodeResult with the specified http status code.<\/td><\/tr><tr><td>Unauthorized()<\/td><td>Creates an UnauthorizedResult with status code 401.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Visit MSDN to know all the members of&nbsp;<a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.web.http.apicontroller(v=vs.118).aspx\" target=\"_blank\" rel=\"noreferrer noopener\">ApiController<\/a>.<\/p>\n\n\n\n<p>Create Custom Result Type<\/p>\n\n\n\n<p>You can create your own custom class as a result type that implements IHttpActionResult interface.<\/p>\n\n\n\n<p>The following example demonstrates implementing IHttpActionResult class.<\/p>\n\n\n\n<p>Example: Create Custom Result Type<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class TextResult : IHttpActionResult<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; string _value;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; HttpRequestMessage _request;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public TextResult(string value, HttpRequestMessage request)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _value = value;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _request = request;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public Task&lt;HttpResponseMessage&gt; ExecuteAsync(CancellationToken cancellationToken)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var response = new HttpResponseMessage()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Content = new StringContent(_value),<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; RequestMessage = _request<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Task.FromResult(response);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Now, you can return TextResult object from the action method as shown below.<\/p>\n\n\n\n<p>Example: Return Custom Result Type<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public IHttpActionResult GetName(int id)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; string name = GetStudentName(id);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; if (String.IsNullOrEmpty(name))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return NotFound();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return new TextResult(name, Request);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Web API Request\/Response Data Formats<\/h1>\n\n\n\n<p>Here, you will learn how Web API handles different formats of request and response data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Media Type<\/h2>\n\n\n\n<p>Media type (aka MIME type) specifies the format of the data as type\/subtype e.g. text\/html, text\/xml, application\/json, image\/jpeg etc.<\/p>\n\n\n\n<p>In HTTP request, MIME type is specified in the request header using&nbsp;<strong>Accept<\/strong>&nbsp;and&nbsp;<strong>Content-Type<\/strong>&nbsp;attribute. The Accept header attribute specifies the format of response data which the client expects and the Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.<\/p>\n\n\n\n<p>For example, if a client wants response data in JSON format then it will send following GET HTTP request with Accept header to the Web API.<\/p>\n\n\n\n<p>HTTP GET Request:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">GET http:\/\/localhost:60464\/api\/student HTTP\/1.1<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">User-Agent: Fiddler<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">Host: localhost:1234<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Accept: application\/json<\/strong><\/pre>\n\n\n\n<p>The same way, if a client includes JSON data in the request body to send it to the receiver then it will send following POST HTTP request with Content-Type header with JSON data in the body.<\/p>\n\n\n\n<p>HTTP POST Request:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">POST http:\/\/localhost:60464\/api\/student?age=15 HTTP\/1.1<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">User-Agent: Fiddler<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">Host: localhost:60464<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Content-Type: application\/json<\/strong><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">Content-Length: 13<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp;<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">{<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; id:1,<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; name:'Steve'<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">}<\/pre>\n\n\n\n<p>Web API converts request data into CLR object and also serialize CLR object into response data based on Accept and Content-Type headers. Web API includes built-in support for JSON, XML, BSON, and form-urlencoded data. It means it automatically converts request\/response data into these formats OOB (out-of the box).<\/p>\n\n\n\n<p>Example: Post Action Method<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>Student<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>int<code> Id { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>string<code> Name { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Post(<\/code>Student<code> student)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/ save student into db<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> insertedStudent = SaveStudent(student);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> insertedStudent;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>As you can see above, the Post() action method accepts Student type parameter, saves that student into DB and returns inserted student with generated id. The above Web API handles HTTP POST request with JSON or XML data and parses it to a Student object based on Content-Type header value and the same way it converts insertedStudent object into JSON or XML based on Accept header value.<\/p>\n\n\n\n<p>The following figure illustrates HTTP POST request in fiddler.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-req-response1.png\" target=\"_blank\"><\/a>Request-Response Data Format<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"919\" height=\"622\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-11.png\" alt=\"\" class=\"wp-image-1831\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-11.png 919w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-11-300x203.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-11-768x520.png 768w\" sizes=\"auto, (max-width: 919px) 100vw, 919px\" \/><\/figure>\n\n\n\n<p>In the above figure, Accept header specifies that it expects response data in XML format and Content-Type specifies that the student data into request body is in the JSON format. The following is the response upon execution of the above request.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/webapi-req-response2.png\" target=\"_blank\"><\/a>Request-Response Data Format<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"904\" height=\"529\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-12.png\" alt=\"\" class=\"wp-image-1832\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-12.png 904w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-12-300x176.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-12-768x449.png 768w\" sizes=\"auto, (max-width: 904px) 100vw, 904px\" \/><\/figure>\n\n\n\n<p>The same way, you can specify different request &amp; response format using accept and content-type headers and Web API will handle them without any additional changes.<\/p>\n\n\n\n<p>The following HTTP POST request sends data in XML format and receives data in JSON format.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/fiddler-req2.png\" target=\"_blank\"><\/a>Web API Request<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"503\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-13.png\" alt=\"\" class=\"wp-image-1833\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-13.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-13-300x161.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-13-768x411.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>The above HTTP POST request will get the following response upon execution.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/fiddler-response2.png\" target=\"_blank\"><\/a>Web API Response<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"834\" height=\"514\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-14.png\" alt=\"\" class=\"wp-image-1834\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-14.png 834w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-14-300x185.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-14-768x473.png 768w\" sizes=\"auto, (max-width: 834px) 100vw, 834px\" \/><\/figure>\n\n\n\n<p>Thus, Web API handles JSON and XML data by default. Learn how Web API formats request\/response data using formatters in the next section.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">ASP.NET Web API: Media-Type Formatters<\/h1>\n\n\n\n<p>As you have seen in the previous section that Web API handles JSON and XML formats based on Accept and Content-Type headers. But, how does it handle these different formats? The answer is: By using Media-Type formatters.<\/p>\n\n\n\n<p>Media type formatters are classes responsible for serializing request\/response data so that Web API can understand the request data format and send data in the format which client expects.<\/p>\n\n\n\n<p>Web API includes following built-in media type formatters.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Media Type Formatter Class<\/td><td>MIME Type<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>JsonMediaTypeFormatter<\/td><td>application\/json, text\/json<\/td><td>Handles JSON format<\/td><\/tr><tr><td>XmlMediaTypeFormatter<\/td><td>application\/xml, text\/json<\/td><td>Handles XML format<\/td><\/tr><tr><td>FormUrlEncodedMediaTypeFormatter<\/td><td>application\/x-www-form-urlencoded<\/td><td>Handles HTML form URL-encoded data<\/td><\/tr><tr><td>JQueryMvcFormUrlEncodedFormatter<\/td><td>application\/x-www-form-urlencoded<\/td><td>Handles model-bound HTML form URL-encoded data<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Retrieve Built-in Media Type Formatters<\/h2>\n\n\n\n<p>As mentioned Web API includes above listed media type formatter classes by default. However, you can also add, remove or change the order of formatters.<\/p>\n\n\n\n<p>The following example demonstrates HTTP Get method that returns all built-in formatter classes.<\/p>\n\n\n\n<p>Example: Retrieve Built-in Formatters in C#<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>FormattersController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>IEnumerable<code>&lt;<\/code>string<code>&gt; Get()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>IList<code>&lt;<\/code>string<code>&gt; formatters = <\/code>new<code> <\/code>List<code>&lt;<\/code>string<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>foreach<code> (<\/code>var<code> item <\/code>in<code> <\/code>GlobalConfiguration<code>.Configuration.Formatters)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; formatters.Add(item.ToString());<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> formatters.AsEnumerable&lt;<\/code>string<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>In the above example,&nbsp;<code>GlobalConfiguration.Configuration.Formatters<\/code>&nbsp;returns MediaTypeFormatterCollection that includes all the formatter classes. The above example returns names of all the formatter classes as shown below.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/formatters1.png\" target=\"_blank\"><\/a>Built-in Media-Type Formatters<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"491\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-15.png\" alt=\"\" class=\"wp-image-1835\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-15.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-15-300x157.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-15-768x401.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<p>Alternatively, MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example demonstrates retrieving media type formatters using MediaTypeFormatterCollection&#8217;s properties.<\/p>\n\n\n\n<p>Example: Retrieve Built-in Formatters in C#<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>FormattersController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> IEnumerable&lt;<\/code>string<code>&gt; Get()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>IList<code>&lt;<\/code>string<code>&gt; formatters = <\/code>new<code> <\/code>List<code>&lt;<\/code>string<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; formatters.Add(<\/code>GlobalConfiguration<code>.Configuration.Formatters.JsonFormatter.GetType().FullName);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; formatters.Add(<\/code>GlobalConfiguration<code>.Configuration.Formatters.XmlFormatter.GetType().FullName);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; formatters.Add(<\/code>GlobalConfiguration<code>.Configuration.Formatters.FormUrlEncodedFormatter.GetType().FullName);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code>return<code> formatters.AsEnumerable&lt;<\/code>string<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above example returns following response to the browser.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/formatters2.png\" target=\"_blank\"><\/a>Media-Type Formatters<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"940\" height=\"386\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-16.png\" alt=\"\" class=\"wp-image-1836\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-16.png 940w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-16-300x123.png 300w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/image-16-768x315.png 768w\" sizes=\"auto, (max-width: 940px) 100vw, 940px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">BSON Formatter<\/h3>\n\n\n\n<p>Web API also supports BSON format. As the name suggests, BSON is binary JSON, it is a binary-encoded serialization of JSON-like documents. Currently there is very little support for BSON and no JavaScript implementation is available for clients running in browsers. This means that it is not possible to retrieve and automatically parse BSON data to JavaScript objects.<\/p>\n\n\n\n<p>Web API includes built-in formatter class BsonMediaTypeFormatter for BSON but it is&nbsp;<strong>disabled<\/strong>&nbsp;by default. Learn more about BSON support in Web API&nbsp;<a href=\"https:\/\/www.asp.net\/web-api\/overview\/formats-and-model-binding\/bson-support-in-web-api-21\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">JSON Formatter<\/h3>\n\n\n\n<p>As mentioned above, Web API includes JsonMediaTypeFormatter class that handles JSON format. The JsonMediaTypeFormatter converts JSON data in an HTTP request into CLR objects (object in C# or VB.NET) and also converts CLR objects into JSON format that is embeded within HTTP response.<\/p>\n\n\n\n<p>Internally, JsonMediaTypeFormatter uses third-party open source library called&nbsp;<a href=\"https:\/\/json.codeplex.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">Json.NET<\/a>&nbsp;to perform serialization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Configure JSON Serialization<\/h3>\n\n\n\n<p>JSON formatter can be configured in WebApiConfig class. The JsonMediaTypeFormatter class includes various properties and methods using which you can customize JSON serialization. For example, Web API writes JSON property names with PascalCase by default. To write JSON property names with camelCase, set the CamelCasePropertyNamesContractResolver on the serializer settings as shown below.<\/p>\n\n\n\n<p>Example: Customize JSON Serialization in C#<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public static<code> <\/code>class<code> <\/code>WebApiConfig<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public static void<code> Register(<\/code>HttpConfiguration<code> config)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;config.Routes.MapHttpRoute(<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: <\/code>\"DefaultApi\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: <\/code>\"api\/{controller}\/{id}\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: <\/code>new<code> { id = RouteParameter.Optional }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/ configure json formatter<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>JsonMediaTypeFormatter<code> jsonFormatter = config.Formatters.JsonFormatter;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; jsonFormatter.SerializerSettings.ContractResolver = <\/code>new<code> <\/code>CamelCasePropertyNamesContractResolver<code>();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">XML Formatter<\/h3>\n\n\n\n<p>The XmlMediaTypeFormatter class is responsible for serializing model objects into XML data. It uses System.Runtime.DataContractSerializer class to generate XML data.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Web API Filters<\/h1>\n\n\n\n<p>Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.<\/p>\n\n\n\n<p>Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.<\/p>\n\n\n\n<p>The following table lists important interfaces and classes that can be used to create Web API filters.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Filter Type<\/td><td>Interface<\/td><td>Class<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>Simple Filter<\/td><td>IFilter<\/td><td>&#8211;<\/td><td>Defines the methods that are used in a filter<\/td><\/tr><tr><td>Action Filter<\/td><td>IActionFilter<\/td><td>ActionFilterAttribute<\/td><td>Used to add extra logic before or after action methods execute.<\/td><\/tr><tr><td>Authentication Filter<\/td><td>IAuthenticationFilter<\/td><td>&#8211;<\/td><td>Used to force users or clients to be authenticated before action methods execute.<\/td><\/tr><tr><td>Authorization Filter<\/td><td>IAuthorizationFilter<\/td><td>AuthorizationFilterAttribute<\/td><td>Used to restrict access to action methods to specific users or groups.<\/td><\/tr><tr><td>Exception Filter<\/td><td>IExceptionFilter<\/td><td>ExceptionFilterAttribute<\/td><td>Used to handle all unhandled exception in Web API.<\/td><\/tr><tr><td>Override Filter<\/td><td>IOverrideFilter<\/td><td>&#8211;<\/td><td>Used to customize the behaviour of other filter for individual action method.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>As you can see, the above table includes class as well as interface for some of the filter types. Interfaces include methods that must be implemented in your custom attribute class whereas filter class has already implemented necessary interfaces and provides virtual methods, so that they can be overridden to add extra logic. For example, ActionFilterAttribute class includes methods that can be overridden. We just need to override methods which we are interested in, whereas if you use IActionFilter attribute than you must implement all the methods.<\/p>\n\n\n\n<p>Visit MSDN to know all the classes and interfaces available in&nbsp;<a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.web.http.filters(v=vs.118).aspx\" target=\"_blank\" rel=\"noreferrer noopener\">System.Web.Http.Filters<\/a>.<\/p>\n\n\n\n<p>Let&#8217;s create simple LogAttribute class for logging purpose to demonstrate action filter.<\/p>\n\n\n\n<p>First, create a LogAttribute class derived from ActionFilterAttribute class as shown below.<\/p>\n\n\n\n<p>Example: Web API Filter Class<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>LogAttribute<code> : <\/code>ActionFilterAttribute <code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> LogAttribute()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>override<code> <\/code>void<code> OnActionExecuting(<\/code>HttpActionContext<code> actionContext)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Trace.WriteLine(<\/code>string<code>.Format(<\/code>\"Action Method {0} executing at {1}\"<code>, actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), <\/code>\"Web API Logs\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>override<code> <\/code>void<code> OnActionExecuted(<\/code>HttpActionExecutedContext<code> actionExecutedContext)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Trace.WriteLine(<\/code>string<code>.Format(<\/code>\"Action Method {0} executed at {1}\"<code>, actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), <\/code>\"Web API Logs\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>In the above example, LogAttribute is derived from ActionFilterAttribute class and overrided OnActionExecuting and OnActionExecuted methods to log in the trace listeners. (You can use your own logging class to log in textfile or other medium.)<\/p>\n\n\n\n<p>Another way of creating LogAttribute class is by implementing IActionFilter interface and deriving Attribute class as shown below.<\/p>\n\n\n\n<p>Example: Web API Filter Class<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>LogAttribute<code> : <\/code>Attribute<code>, <\/code>IActionFilter<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> LogAttribute()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Task<code>&lt;<\/code>HttpResponseMessage<code>&gt; ExecuteActionFilterAsync(<\/code>HttpActionContext<code> actionContext, CancellationToken cancellationToken, <\/code>Func<code>&lt;<\/code>Task<code>&lt;<\/code>HttpResponseMessage<code>&gt;&gt; continuation)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Trace.WriteLine(<\/code>string<code>.Format(<\/code>\"Action Method {0} executing at {1}\"<code>, actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), <\/code>\"Web API Logs\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> result = continuation();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; result.Wait();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Trace.WriteLine(<\/code>string<code>.Format(<\/code>\"Action Method {0} executed at {1}\"<code>, actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), <\/code>\"Web API Logs\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> result;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>bool<code> AllowMultiple<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get { <\/code>return<code> <\/code>true<code>; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>} <\/code><\/pre>\n\n\n\n<p>In the above example, deriving from Attribute class makes it an attribute and implementing IActionFilter makes LogAttribute class as action filter. So now, you can apply [Log] attributes on controllers or action methods as shown below.<\/p>\n\n\n\n<p>Example: Apply Web API Filter on Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>[<\/code>Log<code>]<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> StudentController()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>Student<code> Get()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/provide implementation&nbsp; <code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>So now, it will log all the requests handled by above StudentController. Thus you can create filters for cross-cutting concerns.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Consume Web API in .NET using HttpClient<\/h1>\n\n\n\n<p>The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol. However, WebClient class had some limitations. The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient. Here, we will use HttpClient class in console application to send data to and receive data from Web API which is hosted on local IIS web server. You may use HttpClient in other .NET applications also such as MVC Web Application, windows form application, windows service application etc.<\/p>\n\n\n\n<p>Let&#8217;s see how to consume Web API using HttpClient in the console application.<\/p>\n\n\n\n<p>We will consume the following Web API created in the previous section.<\/p>\n\n\n\n<p>Example: Web API Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Collections.Generic;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Linq;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net.Http;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Web.Http;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">namespace<code> MyWebAPI.Controller<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>public<code> IHttpActionResult GetAllStudents(<\/code>bool<code> includeAddress = <\/code>false<code>)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IList&lt;StudentViewModel&gt; students = <\/code>null<code>;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>using<code> (<\/code>var<code> ctx = <\/code>new<code> SchoolDBEntities())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; students = ctx.Students.Include(<\/code>\"StudentAddress\"<code>).Select(s =&gt; <\/code>new<code> StudentViewModel()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Id = s.StudentID,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FirstName = s.FirstName,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LastName = s.LastName,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Address = s.StudentAddress == <\/code>null<code> || includeAddress == <\/code>false<code> ? <\/code>null<code> : <\/code>new<code> AddressViewModel()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StudentId = s.StudentAddress.StudentID,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Address1 = s.StudentAddress.Address1,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Address2 = s.StudentAddress.Address2,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; City = s.StudentAddress.City,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; State = s.StudentAddress.State<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }).ToList&lt;StudentViewModel&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (students.Count == 0)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> NotFound();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> Ok(students);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>public<code> IHttpActionResult PostNewStudent(StudentViewModel student)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (!ModelState.IsValid)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> BadRequest(<\/code>\"Not a valid data\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>using<code> (<\/code>var<code> ctx = <\/code>new<code> SchoolDBEntities())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ctx.Students.Add(<\/code>new<code> Student()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StudentID = student.Id,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FirstName = student.FirstName,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LastName = student.LastName<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ctx.SaveChanges();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> Ok();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>public<code> IHttpActionResult Put(StudentViewModel student)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (!ModelState.IsValid)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> BadRequest(<\/code>\"Not a valid data\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>using<code> (<\/code>var<code> ctx = <\/code>new<code> SchoolDBEntities())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> existingStudent = ctx.Students.Where(s =&gt; s.StudentID == student.Id).FirstOrDefault&lt;Student&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (existingStudent != <\/code>null<code>)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; existingStudent.FirstName = student.FirstName;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; existingStudent.LastName = student.LastName;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ctx.SaveChanges();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>else<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> NotFound();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> Ok();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>public<code> IHttpActionResult Delete(<\/code>int<code> id)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (id &lt;= 0)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> BadRequest(<\/code>\"Not a valid studet id\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>using<code> (<\/code>var<code> ctx = <\/code>new<code> SchoolDBEntities())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> student = ctx.Students<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .Where(s =&gt; s.StudentID == id)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .FirstOrDefault();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ctx.Entry(student).State = System.Data.Entity.EntityState.Deleted;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ctx.SaveChanges();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> Ok();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p><strong>Step 1:<\/strong><\/p>\n\n\n\n<p>First, create a console application in Visual Studio 2013 for Desktop.<\/p>\n\n\n\n<p><strong>Step 2:<\/strong><\/p>\n\n\n\n<p>Open NuGet Package Manager console from&nbsp;<strong>TOOLS<\/strong>&nbsp;-&gt;&nbsp;<strong>NuGet Package Manager<\/strong>&nbsp;-&gt;&nbsp;<strong>Package Manager Console<\/strong>&nbsp;and execute following command.<\/p>\n\n\n\n<p>Install-Package Microsoft.AspNet.WebApi.Client<\/p>\n\n\n\n<p><strong>Step 3:<\/strong><\/p>\n\n\n\n<p>Now, create a Student model class because we will send and receive Student object to our Web API.<\/p>\n\n\n\n<p>Example: Model Class<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> Student<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>int<code> Id { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>string<code> Name { get; set; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Send GET Request<\/h2>\n\n\n\n<p>The following example sends an HTTP GET request to Student Web API and displays the result in the console.<\/p>\n\n\n\n<p>Example: Send HTTP GET Request using HttpClient<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Collections.Generic;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Linq;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Text;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Threading.Tasks;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net.Http;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net.Http.Headers;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">namespace<code> HttpClientDemo<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>class<code> Program<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>static<code> <\/code>void<code> Main(<\/code>string<code>[] args)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>using<code> (<\/code>var<code> client = <\/code>new<code> HttpClient())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; client.BaseAddress = <\/code>new<code> Uri(<\/code>\"http:\/\/localhost:60464\/api\/\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/HTTP GET<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> responseTask = client.GetAsync(<\/code>\"student\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; responseTask.Wait();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> result = responseTask.Result;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code>if<code> (result.IsSuccessStatusCode)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> readTask = result.Content.ReadAsAsync&lt;Student[]&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; readTask.Wait();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> students = readTask.Result;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>foreach<code> (<\/code>var<code> student <\/code>in<code> students)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(student.Name);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.ReadLine();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>Let&#8217;s understand the above example step by step.<\/p>\n\n\n\n<p>First, we have created an object of HttpClient and assigned the base address of our Web API. The GetAsync() method sends an http GET request to the specified url. The GetAsync() method is asynchronous and returns a Task. Task.wait() suspends the execution until GetAsync() method completes the execution and returns a result.<\/p>\n\n\n\n<p>Once the execution completes, we get the result from Task using Task.result which is HttpResponseMessage. Now, you can check the status of an http response using IsSuccessStatusCode. Read the content of the result using ReadAsAsync() method.<\/p>\n\n\n\n<p>Thus, you can send http GET request using HttpClient object and process the result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Send POST Request<\/h2>\n\n\n\n<p>Similarly, you can send HTTP POST request using PostAsAsync() method of HttpClient and process the result the same way as GET request.<\/p>\n\n\n\n<p>The following example send http POST request to our Web API. It posts Student object as json and gets the response.<\/p>\n\n\n\n<p>Example: Send HTTP POST Request using HttpClient<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Collections.Generic;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Linq;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Text;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Threading.Tasks;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net.Http;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">using<code> System.Net.Http.Headers;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">namespace<code> HttpClientDemo<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>class<code> Program<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>static<code> <\/code>void<code> Main(<\/code>string<code>[] args)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> student = <\/code>new<code> Student() { Name = <\/code>\"Steve\"<code> };<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> postTask = client.PostAsJsonAsync&lt;Student&gt;(<\/code>\"student\"<code>, student);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; postTask.Wait();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> result = postTask.Result;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (result.IsSuccessStatusCode)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> readTask = result.Content.ReadAsAsync&lt;Student&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; readTask.Wait();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>var<code> insertedStudent = readTask.Result;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(<\/code>\"Student {0} inserted with id: {1}\"<code>, insertedStudent.Name, insertedStudent.Id);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>else<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(result.StatusCode);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The following table lists all the methods of HttpClient to send different HTTP requests.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Method Name<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>GetAsync<\/td><td>Sends a GET request to the specified Uri as an asynchronous operation.<\/td><\/tr><tr><td>GetByteArrayAsync<\/td><td>Sends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation.<\/td><\/tr><tr><td>GetStreamAsync<\/td><td>Sends a GET request to the specified Uri and returns the response body as a stream in an asynchronous operation.<\/td><\/tr><tr><td>GetStringAsync<\/td><td>Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation.<\/td><\/tr><tr><td>PostAsync<\/td><td>Sends a POST request to the specified Uri as an asynchronous operation.<\/td><\/tr><tr><td>PostAsJsonAsync<\/td><td>Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.<\/td><\/tr><tr><td>PostAsXmlAsync<\/td><td>Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as XML.<\/td><\/tr><tr><td>PutAsync<\/td><td>Sends a PUT request to the specified Uri as an asynchronous operation.<\/td><\/tr><tr><td>PutAsJsonAsync<\/td><td>Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON.<\/td><\/tr><tr><td>PutAsXmlAsync<\/td><td>Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as XML.<\/td><\/tr><tr><td>DeleteAsync<\/td><td>Sends a DELETE request to the specified Uri as an asynchronous operation.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h1 class=\"wp-block-heading\">Configure Dependency Injection with Web API<\/h1>\n\n\n\n<p>Here you will learn how to configure and use IoC container for dependency injection with Web API.<\/p>\n\n\n\n<p>There are many IoC containers available for dependency injection such as Ninject, Unity, castleWidsor, structuremap etc. Here we will use Ninject for dependency injection.<\/p>\n\n\n\n<p>The following is our sample Web API that uses instance of a class that implements IRepository.<\/p>\n\n\n\n<p>Example: Simple Web API Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentController<code> : <\/code>ApiController<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>IRepository<code> _repo = <\/code>null<code>;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> StudentController(<\/code>IRepository<code> repo)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _repo = repo;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>IList<code>&lt;<\/code>Student<code>&gt; Get()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code>&nbsp; _repo.GetAll();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The following are IRepository and StudentRepository class.<\/p>\n\n\n\n<p>Example: Repository<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>interface<code> <\/code>IRepository<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>IList<code>&lt;<\/code>Student<code>&gt; GetAll();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>StudentRepository<code> : <\/code>IRepository<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>IList<code>&lt;<\/code>Student<code>&gt; GetAll()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/return students from db here<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>Now, let&#8217;s use Ninject which will inject StudentRepository class in StudentController.<\/p>\n\n\n\n<p>First of all, you need to install Ninject library for Web API using NuGet. To do this, right click on your project in the solution explorer -&gt; click on&nbsp;<strong>Manage NuGet packages..<\/strong>. This will open NuGet popup. Now search for webapicontrib in the search box as shown below.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/configure-DI-1.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Web API Configuration<\/p>\n\n\n\n<p>As you can see, this will list all the IoC containers for Web API. Select WebApiContrib.IoC.Ninject and click&nbsp;<strong>Install<\/strong>.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/configure-DI-2.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Web API Configuration<\/p>\n\n\n\n<p>Now, you need to install Ninject.Extensions.ChildKernel. Search for it and install it.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/configure-DI-3.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Web API Configuration<\/p>\n\n\n\n<p>So now after installing necessary packages for Ninject, we need to configure it.<\/p>\n\n\n\n<p>In order to use dependency injection with Web API, we need to create a resolver class that implements IDependencyResolver interface. Here, we have created NinjectResolver class in Infrastructure folder in our Web API project as shown below.<\/p>\n\n\n\n<p>Example: DI Resolver<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>NinjectResolver<code> : <\/code>IDependencyResolver<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>IKernel<code> kernel;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> NinjectResolver() : <\/code>this<code>(<\/code>new<code> <\/code>StandardKernel<code>()) <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;{ <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> NinjectResolver(<\/code>IKernel<code> ninjectKernel, <\/code>bool<code> scope = <\/code>false<code>)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kernel = ninjectKernel;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>if<code> (!scope)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AddBindings(kernel);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>IDependencyScope<code> BeginScope()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> <\/code>new<code> <\/code>NinjectResolver<code>(AddRequestBindings(<\/code>new<code> <\/code>ChildKernel<code>(kernel)), <\/code>true<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>object<code> GetService(<\/code>Type<code> serviceType)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> kernel.TryGet(serviceType);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>IEnumerable<code>&lt;<\/code>object<code>&gt; GetServices(<\/code>Type<code> serviceType)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> kernel.GetAll(serviceType);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>void<code> Dispose()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>void<code> AddBindings(<\/code>IKernel<code> kernel)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/ singleton and transient bindings go here<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>IKernel<code> AddRequestBindings(<\/code>IKernel<code> kernel)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kernel.Bind&lt;<\/code>IRepository<code>&gt;().To&lt;<\/code>StudentRepository<code>&gt;().InSingletonScope();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> kernel;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>Now, we need to configure NijectResolver with Web API in the WebApiConfig class as shown below.<\/p>\n\n\n\n<p>Example: Set DI Resolver<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>static<code> <\/code>class<code> <\/code>WebApiConfig<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>static<code> <\/code>void<code> Register(<\/code>HttpConfiguration<code> config)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.DependencyResolver = <\/code>new<code> <\/code>NinjectResolver<code>();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.MapHttpAttributeRoutes();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name: <\/code>\"DefaultApi\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; routeTemplate: <\/code>\"api\/{controller}\/{id}\"<code>,<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; defaults: <\/code>new<code> { id = RouteParameter.Optional }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>As you can see above, HttpConfiguration.DependencyResolver is set to NinjectResolver. So now, Web API will use NinjectResolver class to create the objects it needs.<\/p>\n\n\n\n<p>Thus, you can configure IoC container with Web API.<\/p>\n\n\n\n<p>Web API Hosting<\/p>\n\n\n\n<p>In this section, you will learn how to host a Web API.<\/p>\n\n\n\n<p>The Web API application can be hosted in two ways.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>IIS Hosting<\/li>\n\n\n\n<li>Self Hosting<\/li>\n<\/ul>\n\n\n\n<p>IIS Hosting<\/p>\n\n\n\n<p>Web API can be hosted under IIS, in the same way as a web application. You have learned to create a Web API in the previous section. As you have seen there, a Web API is created with ASP.NET MVC project by default. So, when you host your MVC web application under IIS it will also host Web API that uses the same base address.<\/p>\n\n\n\n<p>Self Hosting<\/p>\n\n\n\n<p>You can host a Web API as separate process than ASP.NET. It means you can host a Web API in console application or windows service or OWIN or any other process that is managed by .NET framework.<\/p>\n\n\n\n<p>You need to do following steps in order to self-host a web API.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>Use HttpConfiguration to configure a Web API<\/li>\n\n\n\n<li>Create HttpServer and start listening to incoming http requests<\/li>\n<\/ol>\n\n\n\n<p>Let&#8217;s see how to host a simple Web API in console application.<\/p>\n\n\n\n<p>First of all, create a console project in Visual Studio 2012 for Desktop (or latter version).<\/p>\n\n\n\n<p>Note: You must open Visual Studio in Administration mode.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/create-console-app.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Create&nbsp;Console&nbsp;Application<\/p>\n\n\n\n<p>Now, you need to add Microsoft ASP.NET Web API 2.x Self Host package using NuGet. Right click on project in the Solution Explorer window and select&nbsp;<strong>Manage NuGet Packges..<\/strong><\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/manage-nuget.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Open NuGet Manager<\/p>\n\n\n\n<p>In the Manage NuGet Packages window, select Online option in left pan and search for web-api. This will list all the packages for Web API. Now, look for&nbsp;<strong>Microsoft ASP.NET Web API 2.2 Self Host<\/strong>&nbsp;package and click&nbsp;<strong>Install<\/strong>.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/install-selfhost.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Install Web API Self Host Package<\/p>\n\n\n\n<p>Click on&nbsp;<strong>Accept<\/strong>&nbsp;button in the License Acceptance window.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/accept-selfhost.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Accept License Agreement<\/p>\n\n\n\n<p>This will install the package into your project.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/installing-selfhost.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Install Web API self Hosting Package<\/p>\n\n\n\n<p>Now write the following code in the Main() method of Program class.<\/p>\n\n\n\n<p>Example: Self-Hosting Web API<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>class Program<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; static void Main(string[] args)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var config = new HttpSelfHostConfiguration(&#8220;http:\/\/localhost:1234&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var task = server.OpenAsync();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; task.Wait();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(&#8220;Web API Server has started at http:\/\/localhost:1234&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.ReadLine();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the above code, first we created an object of HttpSelfHostConfiguration class by passing uri location. Then, we created an object of HttpSelfHostServer by passing config and HttpMessageHandler object. And then we started listening for incoming request by calling server.OpenAsync() method. This will listen requests asynchronously, so it will return Task object.<\/p>\n\n\n\n<p>Create&nbsp;MyWebAPIMessageHandler&nbsp;class and write the following code.<\/p>\n\n\n\n<p>Example: MessageHandler<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>class MyWebAPIMessageHandler : HttpMessageHandler<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var task = new Task&lt;HttpResponseMessage&gt;(() =&gt; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var resMsg = new HttpResponseMessage();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; resMsg.Content = new StringContent(&#8220;Hello World!&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return resMsg;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; task.Start();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return task;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Thus, you can create simple console application and host simple Web API that returns &#8220;Hello World!&#8221; to every request.<\/p>\n\n\n\n<p>Run the console application using Ctrl + F5.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/run-console-app.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Run Console Application<\/p>\n\n\n\n<p>Open web browser and enter&nbsp;http:\/\/localhost:1234\/&nbsp;and see the result.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/webapi\/response-in-browser.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Response in Browser<\/p>\n\n\n\n<p>Hosting Controller Infrastructure<\/p>\n\n\n\n<p>You can use the same ASP.NET routing and ApiController capabilities of ASP.NET Hosting in self hosting.<\/p>\n\n\n\n<p>In the same self hosting console application, create simple HomeController class as shown below.<\/p>\n\n\n\n<p>Example: Web API Controller<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>public class HomeController : ApiController<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public string Get() {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;Hello World!&#8221;;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public string Get(string name) {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;Hello &#8221; + name;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Now, in the Main() method, configure a default route using config object as shown below.<\/p>\n\n\n\n<p>Example: Self Hosting Web API<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<p>static void Main(string[] args)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; var config = new HttpSelfHostConfiguration(&#8220;http:\/\/localhost:1234&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; config.Routes.MapHttpRoute(&#8220;default&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8220;api\/{controller}\/{id}&#8221;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new { controller = &#8220;Home&#8221;, id = RouteParameter.Optional });<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; var server = new HttpSelfHostServer(config);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; var task = server.OpenAsync();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; task.Wait();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; Console.WriteLine(&#8220;Web API Server has started at http:\/\/localhost:1234&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; Console.ReadLine();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Please notice that we removed an object of MessageHandler when creating an object of HttpSelfHostServer.<\/p>\n\n\n\n<p>Now, run the console application by pressing&nbsp;<em>Ctrl + F5<\/em>. Open the browser and enter&nbsp;http:\/\/localhost:1234\/api&nbsp;or&nbsp;http:\/\/localhost:1234\/api?name=steve&nbsp;and see the result as shown below.<\/p>\n\n\n\n<p><strong>Web API Interview Questions<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>1.&nbsp;What is ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP-based services. Clients dealing with mobile applications and web browsers can consume Web API.<\/p>\n\n\n\n<p><strong>2.&nbsp;What are the differences between Web API and WCF REST API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message queues, one-way messaging, and duplex communication. WEB API supports any media format, even XML and JSON, while WCF supports SOAP and XML formats. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for developing service-oriented applications. To run Web API, there is no configuration required, while in the case of WCF, a lot of configuration is required to run it.<\/p>\n\n\n\n<p><strong>3.&nbsp;What are the advantages of using ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The advantages of using ASP.Net Web API are mentioned below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It completes support for routing<\/li>\n\n\n\n<li>Is works as HTTP using standard HTTP verbs such as GET, DELETE, POST, PUT, to name a few, for all CRUD operations<\/li>\n\n\n\n<li>It can be hosted in IIS as well as self-host outside of IIS<\/li>\n\n\n\n<li>It supports OData<\/li>\n\n\n\n<li>It supports validation and model binding<\/li>\n\n\n\n<li>The response is generated in XML or JSON format by using MediaTypeFormatter<\/li>\n<\/ul>\n\n\n\n<p><strong>4.&nbsp;What are the several return types in ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The various return types in ASP.Net Web API are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>IHttpActionResult<\/li>\n\n\n\n<li>HttpResponseMessage<\/li>\n\n\n\n<li>Void<\/li>\n\n\n\n<li>Other Type \u2013 string, int, or other entity types.<\/li>\n<\/ul>\n\n\n\n<p><strong>5.&nbsp;What is ASP.Net Web API routing?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: It is the process that determines the action and controller that should be called.<\/p>\n\n\n\n<p>The ways to incorporate routing in Web API include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Attribute based routing<\/li>\n\n\n\n<li>Convention based routing<\/li>\n<\/ul>\n\n\n\n<p><strong>6.&nbsp;What are Media type formatters in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The Media type formatter in Web API include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>MediaTypeFormatter \u2013 It is the base class that helps to handle serializing and deserializing strongly-typed objects.<\/li>\n\n\n\n<li>BefferedMediaTypeFormatter \u2013 It signifies a helper class to allow asynchronous formatter on top of the asynchronous formatter infrastructure.<\/li>\n<\/ul>\n\n\n\n<p><strong>7.&nbsp;What is the CORS issue in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin restriction for JavaScript. Same-origin means JavaScript only makes AAJAX call for web pages within the same-origin.<\/p>\n\n\n\n<p>You have to install the CORS nuget package by using Package Manager Console to enable CORS in Web API.<\/p>\n\n\n\n<p>Open WebAPIConfig.cs file<\/p>\n\n\n\n<p>add config.EnableCors();<\/p>\n\n\n\n<p>Add EnableCors attribute to the Controller class and define the origin.<\/p>\n\n\n\n<p>[EnableCors(origins: \u201c\u201d, headers: \u201c*\u201d, methods: \u201c*\u201d)].<\/p>\n\n\n\n<p><strong>8.&nbsp;How to secure an ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: To secure an ASP.Net Web API, we need to control the Web API and decide who can access the API and who cannot access it. Web API can be accessed by anyone who knows about the URL.<\/p>\n\n\n\n<p><strong>9.&nbsp;What are the differences between HTTP Get and HTTP Post?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: GET and POST are two important verbs of HTTP.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Parameters of GET are included in the URL; while parameters of POST are included in the body<\/li>\n\n\n\n<li>GET requests do not make any changes to the server; while POST does make changes to the server<\/li>\n\n\n\n<li>A GET request is idempotent; while a POST request is non-idempotent<\/li>\n\n\n\n<li>In a GET request, data is sent in plain text; binary and text data are sent<\/li>\n<\/ul>\n\n\n\n<p><strong>10. How can Web API be used?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Web API can easily be used with ASP.Net Forms. You can add Web API Controller and route in Application Start method in Global.asax file.<\/p>\n\n\n\n<p><strong>11.Exception filters in ASP.Net Web API<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Exception filters in Web API help in implementing IExceptionFilters interface. They perform when an action throws an exception at any point.<\/p>\n\n\n\n<p><strong>12. Do we return Views from ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: No, it is not possible as Web API creates an HTTP-based service. It is mostly available in the MVC application.<\/p>\n\n\n\n<p><strong>13. What is new in ASP.Net Web API 2.0?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The features introduced in&nbsp;<a href=\"https:\/\/www.mygreatlearning.com\/blog\/dot-net-interview-questions\/\" target=\"_blank\" rel=\"noreferrer noopener\">ASP.NET<\/a>&nbsp;Web API framework v2.0 are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Attribute Routing<\/li>\n\n\n\n<li>External Authentication<\/li>\n\n\n\n<li>CORS (Cross-Origin Resource Sharing)<\/li>\n\n\n\n<li>OWIN (Open Web Interface for .NET) Self Hosting<\/li>\n\n\n\n<li>IHttpActionResult<\/li>\n\n\n\n<li>Web API Odata<\/li>\n<\/ul>\n\n\n\n<p><strong>14. How do we limit access to methods with an HTTP verb in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: An attribute has to be added as shown below:<\/p>\n\n\n\n<p>[HttpGet]<\/p>\n\n\n\n<p>public HttpResponseMessage Test()<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>HttpResponseMessage response = new HttpResponseMessage();<\/p>\n\n\n\n<p>\/\/\/<\/p>\n\n\n\n<p>return response;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>[HttpPost]<\/p>\n\n\n\n<p>public void Save([FromBody]string value)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>15. How do we make sure that Web API returns data in JSON format only?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: To ensure that web API returns data in JSON format only, open \u201cWebApiConfig.cs\u201d file as well as add the below line:<\/p>\n\n\n\n<p>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\u201capplication\/json\u201d))<\/p>\n\n\n\n<p>To&nbsp;<a href=\"https:\/\/www.mygreatlearning.com\/json-format\/free-courses?gl_blog_id=38387\" target=\"_blank\" rel=\"noreferrer noopener\">learn JSON format<\/a>, you can also take up free online courses that will help you enhance your basic skills about the same.<\/p>\n\n\n\n<p><strong>16. How to provide Alias name for an action method in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: By adding an attribute ActionName, an Alias name can be provided:<\/p>\n\n\n\n<p>[ActionName(\u201cInertUserData\u201d)]<\/p>\n\n\n\n<p>\/\/ POST api\/<\/p>\n\n\n\n<p>public void Post([FromBody]string value)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>17. How can we handle errors in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Handling errors or exceptions in Web API can be done with the help of the following classes \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Using HttpResponseException \u2013This exception class helps to return the HTTP status code specified in the exception Constructor.<\/li>\n\n\n\n<li>Using HttpError \u2013 This exception class helps to return meaningful error code to the client as HttpResponseMessage.<\/li>\n\n\n\n<li>Using Exception filters \u2013 Exception filters help in catching unhandled exceptions or errors generated in Web API and they can be used whenever the controller action method throws the unhandled error.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>18. How to host Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: There are two ways how Web API application can be hosted:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Self Hosting&nbsp;<\/li>\n\n\n\n<li>IIS Hosting&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>19. How to consume Web API using HTTPClient?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: HTTPClient is introduced in HTTPClient class for communicating with ASP.Net Web API. This HTTPClient class is used either in a console application or in an MVC application.<\/p>\n\n\n\n<p><strong>20. Explain oData with ASP.Net Web API.&nbsp;<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: OData is the acronym for Open Data Protocol. It is a Rest-based data access protocol. OData provides a way to manipulate data by making use of CRUD operations. ASP.Net Web API supports OData V3 and V4.<\/p>\n\n\n\n<p>To use OData in ASP.Net Web API, you would need an OData package. You have to run the below command in the Package Manager Console.<\/p>\n\n\n\n<p>Install-Package Microsoft.AspNet.Odata<\/p>\n\n\n\n<p><strong>21. Can we consume Web API 2 in C# console application?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Yes, Web API 2 can be consumed in Console Application, MVC, Angular JS, or any other application.<\/p>\n\n\n\n<p><strong>22. Perform Web API 2 CRUD operation using Entity Framework.<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: CRUD operation can be performed by using entity framework with Web API.<\/p>\n\n\n\n<p><strong>23. How to enable HTTPs in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: ASP.Net Web API runs over HTTP protocol. You can create a class and get a class with AuthorizationFilterAttribute. Now check if the requested URL has HTTPs.<\/p>\n\n\n\n<p><strong>24. How to implement Basic Authentication in ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Basic Authentication in ASP.Net Web API can be implemented where the client sends a request with an Authorization header and the word Basic. In Basic Authentication, the Authorization header contains the word Basic followed by a base 64 encoded string.<\/p>\n\n\n\n<p>The syntax for Basic Authentication \u2013<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>1<\/td><td>Authorization: Basic username: password<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>25. What is Token Based Authentication in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-based approach.<\/p>\n\n\n\n<p><strong>26. What is content negotiation in .Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: In ASP.Net Web API, content negotiation is done on the server side. This helps in determining the media type formatter, especially when it is about returning the response to an incoming request.<\/p>\n\n\n\n<p><strong>27. What is ASP.Net identity?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: ASP.Net identity is the membership management framework that Microsoft provides. It is very easily incorporated with Web API. This can help you to build a secure HTTP service.<\/p>\n\n\n\n<p><strong>28. What is Bearer Authentication in .Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Bearer authentication is also known as Token-based authentication.<\/p>\n\n\n\n<p><strong>29. What is REST?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A:&nbsp;<a href=\"https:\/\/www.mygreatlearning.com\/blog\/rest-api-interview-questions\/\" target=\"_blank\" rel=\"noreferrer noopener\">REST&nbsp;<\/a>stands for Representational State Transfer. This is an architectural pattern that helps in exchanging data over a disseminated environment.<\/p>\n\n\n\n<p>REST architectural pattern treats all the services as resources and a client can access these resources by using HTTP protocol methods which include PUT, GET, POST, and DELETE.<\/p>\n\n\n\n<p><strong>30. What is Not REST?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The mentioned below are not REST:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A standard<\/li>\n\n\n\n<li>A protocol<\/li>\n\n\n\n<li>3. A replacement of SOAP<\/li>\n<\/ul>\n\n\n\n<p><strong>31. What are the differences between REST and SOAP?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Here are some differences between&nbsp;<a href=\"https:\/\/www.mygreatlearning.com\/blog\/rest-vs-soap\/\" target=\"_blank\" rel=\"noreferrer noopener\">REST and SOAP<\/a>:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td><strong>SOAP<\/strong><\/td><td><strong>REST<\/strong><\/td><\/tr><\/thead><tbody><tr><td>SOAP stands for Simple Object Access Protocol<\/td><td>REST stands for Representational State Transfer.<\/td><\/tr><tr><td>SOAP is a protocol, called an XML<\/td><td>REST is not a protocol but you can call it an architectural pattern example which is used for resource-based architecture.<\/td><\/tr><tr><td>SOAP specifies both stateless as well as state-full implementation<\/td><td>REST is completely stateless.<\/td><\/tr><tr><td>SOAP applies message formats like XML;<\/td><td>REST does not apply message formats like XML or JSON.<\/td><\/tr><tr><td>To expose the service, SOAP uses interfaces and named operations;<\/td><td>REST uses URI and methods like POST, GET, PUT, and DELETE for exposing resources (service).<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>32. What are the differences between ASP.NET MVC and ASP.NET Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: MVC is used to create web applications that can return views as well as data, while ASP.NET Web API is used to create restful HTTP services simply, which returns only data and no view. In MVC, the request is mapped to the actions name, while the request is mapped to the actions based on HTTP verbs in Web API.<\/p>\n\n\n\n<p><strong>33. Is it true that ASP.NET Web API has replaced WCF?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: It is not true! It is rather just another way to build non-SOAP-based services like plain XML or JSON strings. It comes with additional advantages such as using HTTP\u2019s full features and reaching more clients such as mobile devices, etc.<\/p>\n\n\n\n<p><strong>34. Explain media Formatters in Web API 2<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: These are classes that are responsible for response data. The Web API understands the request data format as well as sends data in the format as expected by the clients.<\/p>\n\n\n\n<p><strong>35. Which protocol is supported by Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A:&nbsp; The only protocol supported by Web API is HTTP. Therefore, it can be consumed by a&nbsp; client that supports HTTP protocol.<\/p>\n\n\n\n<p><strong>36. What are the similarities between MVC and Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Both&nbsp;<a href=\"https:\/\/www.mygreatlearning.com\/blog\/a-guide-to-mvc-architecture\/\" target=\"_blank\" rel=\"noreferrer noopener\">MVC<\/a>&nbsp;and Web API are based on the principle of Separation of concerns and concepts like controllers, routing, and models.<\/p>\n\n\n\n<p><strong>37. What are the differences between MVC and Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: MVC is used for developing applications that come with User interfaces. The Views in MVC are used to develop a User Interface. Web API is used for developing HTTP services. To fetch data, the Web API methods are called by other applications.<\/p>\n\n\n\n<p><strong>38. Who can consume Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Web API is consumed by a client that supports HTTP verbs such as DELETE, GET, PUT, and POST. They can quite easily be consumed by a client as Web API services do not need any configuration. Web API can be consumed very easily by portable devices.<\/p>\n\n\n\n<p><strong>39. How are Requests mapped to Action methods in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: As Web API uses HTTP verbs, a client that can consume a Web API that needs ways to call the Web API method. A client can use the HTTP verbs to call the action methods of the Web API.<\/p>\n\n\n\n<p>Take a look at the example given below. In order to call a method like GetEmployee, client can use a jQuery method like:<\/p>\n\n\n\n<p>$.get(\u201c\/api\/Employees\/1\u201d, null, function(response)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>$(\u201c#employees\u201d).html(response);<\/p>\n\n\n\n<p>});<\/p>\n\n\n\n<p>Therefore, the method name above has no mention. As an alternative, GetEmployee method can be called by using the GET HTTP verb.<\/p>\n\n\n\n<p>The GetEmployee method can be defined as:<\/p>\n\n\n\n<p>&nbsp;[HttpGet]<\/p>\n\n\n\n<p>&nbsp;public void GetEmployee(int id)<\/p>\n\n\n\n<p>&nbsp;{<\/p>\n\n\n\n<p>StudentRepository.Get(id);<\/p>\n\n\n\n<p>&nbsp;}<\/p>\n\n\n\n<p>As the GetEmployee method can be seen decorated with the [HttpGet] attribute, different verbs to map the different HTTP requests have to be used:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>HttpGet<\/li>\n\n\n\n<li>HttpPut&nbsp;<\/li>\n\n\n\n<li>HttpPost<\/li>\n\n\n\n<li>HttpDelete<\/li>\n<\/ul>\n\n\n\n<p><strong>40. Can the HTTP request be mapped to the action method without using the HTTP attribute?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: For the action method, there are two ways to map the HTTP request. The first way is using the trait on the action method. The second way is naming the method that starts with the HTTP verb. Taking as an example, to define a GET method, can be defined as:<\/p>\n\n\n\n<p>public void GetEmployee(int id)<\/p>\n\n\n\n<p>&nbsp;{<\/p>\n\n\n\n<p>StudentRepository.Get(id);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As it can start with GET, the above-mentioned method can be automatically mapped with the GET request.<\/p>\n\n\n\n<p><strong>41. How to add certificates to a website?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: To add the certificate to the website, you can follow the steps mentioned below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You have to go to run type command mmc<\/li>\n\n\n\n<li>Now click on Ok<\/li>\n\n\n\n<li>The certificate add window is open now<\/li>\n<\/ul>\n\n\n\n<p><strong>42. Write a LINQ code for authenticating the user?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: public static bool Login(string UN, string pwd)<\/p>\n\n\n\n<p>{StudentDBEntities students = new StudentDBEntities()students.sudent.Any(e =&gt; e.UserName.Equals(UN) &amp;&amp; e=&gt;e.Password.Equlas(UN)) \/\/ students has more than one table}<\/p>\n\n\n\n<p><strong>43. How to navigate another page in jQuery?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: using widow.location.href = \u201c~\/homw.html\u201d;<\/p>\n\n\n\n<p><strong>44. How to enable SSL to ASP.NET web?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: In order to enable SSL to ASP.NET web, you can click on project properties where you can see this option.<\/p>\n\n\n\n<p><strong>45. How to mention Roles and users using Authorize attribute in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>\/\/ Restrict by Name<\/p>\n\n\n\n<p>[Authorize(Users=\u201dShiva,Jai\u201d)]<\/p>\n\n\n\n<p>public class StudentController : ApiController{}<\/p>\n\n\n\n<p>\/\/ Restrict by Role[Authorize(Roles=\u201dAdministrators\u201d)]<\/p>\n\n\n\n<p>public class StudnetController : ApiController{}<\/p>\n\n\n\n<p><strong>46. Can we apply constraints at the route level?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Yes, it can be applied.<\/p>\n\n\n\n<p>[Route(\u201cstudents\/{id:int}\u201d]<\/p>\n\n\n\n<p>public User GetStudentById(int id) { \u2026 }<\/p>\n\n\n\n<p>[Route(\u201cstudents\/{name}\u201d]<\/p>\n\n\n\n<p>public User GetStudentByName(string name) { \u2026 }<\/p>\n\n\n\n<p>You can select the first route whenever the \u201cid\u201d segment of the URI is an integer. Or else, you can choose the second route.<\/p>\n\n\n\n<p><strong>47. How to enable attribute routing?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the WebApi config file.<\/p>\n\n\n\n<p>public static void Register(HttpConfiguration config)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>\/\/ Web API routes<\/p>\n\n\n\n<p>config.MapHttpAttributeRoutes();<\/p>\n\n\n\n<p>\/\/ Other Web API configuration not shown.<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>48. How parameters get the value in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: Parameters get value in Web API in the following way:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Request body<\/li>\n\n\n\n<li>URI<\/li>\n\n\n\n<li>Custom Binding<\/li>\n<\/ul>\n\n\n\n<p><strong>49. Why is the \u201capi\/\u201d segment used in Web API routing?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: \u201capi\/\u201d segment is used to avoid collisions with ASP.NET MVC routing<\/p>\n\n\n\n<p><strong>50. Is it possible to have MVC kind of routing in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: It is possible to implement MVC kind of routing in Web API.<\/p>\n\n\n\n<p><strong>51. Where is the route defined in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: It is placed in the App_Start directory.<\/p>\n\n\n\n<p>App_Start \u2013&gt; WebApiConfig.cs<\/p>\n\n\n\n<p>routes.MapHttpRoute(<\/p>\n\n\n\n<p>name: \u201cmyroute\u201d,<\/p>\n\n\n\n<p>routeTemplate: \u201capi\/{controller}\/{id}\u201d,<\/p>\n\n\n\n<p>defaults: new { id = RouteParameter.Optional }<\/p>\n\n\n\n<p>);<\/p>\n\n\n\n<p><strong>52. How do you construct HtmlResponseMessage?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>public class TestController : ApiController<\/p>\n\n\n\n<p>A: To construct HtmlResponseMessage, you can consider the following way:<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>public HttpResponseMessage Get()<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, \u201cvalue\u201d);<\/p>\n\n\n\n<p>response.Content = new StringContent(\u201cTesting\u201d, Encoding.Unicode);<\/p>\n\n\n\n<p>response.Headers.CacheControl = new CacheControlHeaderValue()<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>MaxAge = TimeSpan.FromMinutes(20)<\/p>\n\n\n\n<p>};<\/p>\n\n\n\n<p>return response;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>53. What are the default media types supported by Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON. The other media types supported can be done by writing a media formatter.<\/p>\n\n\n\n<p><strong>54. What is the disadvantage of \u201cOther Return Types\u201d in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: The major disadvantage of \u201cOther Return Types\u201d in Web API is that error codes like 404 errors will not directly be returned.<\/p>\n\n\n\n<p><strong>55. What is the namespace for IHttpActionResult return type in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>A: System.Web.Http.Results namespace<\/p>\n\n\n\n<p><strong>56. Why is Web API important?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>We have several other technologies similar to Web API yet it is the most important and preferred over others for several reasons \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Web API has the most lightweight architecture and provides an easy interface for websites and client applications to access data.&nbsp;<\/li>\n\n\n\n<li>It uses low bandwidth. This makes it ideal for even small bandwidth devices, for instance, smartphones.<\/li>\n\n\n\n<li>It can create non-SOAP-based HTTP services.<\/li>\n\n\n\n<li>It can be consumed by a range of clients including web browsers, desktop and mobile applications.<\/li>\n\n\n\n<li>Web API is based on HTTP which makes it convenient to define, consume or expose using REST-ful services.&nbsp;<\/li>\n\n\n\n<li>It fits best with HTTP verbs for operations such as Create, Read, Delete or Update.<\/li>\n\n\n\n<li>Web API is more useful from the business point of view and finds its applications in UI\/UX to increase web traffic and interest in a company\u2019s services or products.&nbsp;<\/li>\n\n\n\n<li>It can support a plethora of text and media formats such as JSON, XML, etc.&nbsp;<\/li>\n\n\n\n<li>It can also support Open Data (OData) protocol.&nbsp;<\/li>\n\n\n\n<li>It is most suitable for the MVC pattern which makes it ideal for experienced developers in that pattern.&nbsp;<\/li>\n\n\n\n<li>It can be easily built using technologies such as ASP.NET, JAVA, etc.&nbsp;<\/li>\n\n\n\n<li>It is considered the best to create resource-oriented services.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>57. Which .NET framework supports Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>The .NET framework version supported by Web API includes version 4.0 and above.&nbsp;<\/p>\n\n\n\n<p><strong>58. Which open-source library is supported by Web API for JSON serialization?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API.&nbsp;<\/p>\n\n\n\n<p><strong>59. What are the advantages of using REST in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>REST offers numerous advantages in Web API that include \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Lightweight architecture and easy to use&nbsp;<\/li>\n\n\n\n<li>Offers flexibility<\/li>\n\n\n\n<li>Allows less data transfer between client and server<\/li>\n\n\n\n<li>Handles various types of data formats<\/li>\n\n\n\n<li>Its lightweight architecture makes it optimal for use in mobile applications<\/li>\n\n\n\n<li>Uses simple HTTP calls for inter-machine communication<\/li>\n<\/ul>\n\n\n\n<p><strong>60. When do we need to choose ASP.NET Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>We are moving web-based services toward mobile applications in today\u2019s hyper-connected digital world. That means we need a lightweight, secure, safe, and compatible API with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by many clients, including browsers and modern devices such as mobile phones, tablets, etc.<\/p>\n\n\n\n<p><strong>61. What do you understand by TestApi in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>TestAPi in Web API refers to a utility library that allows developers to create testing tools as well as automate tests for a .NET application.&nbsp;<\/p>\n\n\n\n<p><strong>62. How can we handle an error using HttpError in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>The HttpError method is used in Web API to throw the response body\u2019s error information. One can also use the \u201cCreateErrorResponse\u201d method along with this one.&nbsp;<\/p>\n\n\n\n<p><strong>63. Can we consume Web API 2 in the C# console application?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any other application.<\/p>\n\n\n\n<p><strong>64. How to implement Basic Authentication in ASP.Net Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Basic Authentication in ASP.Net Web API is one where the client will send a request using the word Basic with an Authorization header, followed by a base 64 encoded string.<\/p>\n\n\n\n<p>The syntax for Basic Authentication \u2013<\/p>\n\n\n\n<p>Authorization: Basic username: password<\/p>\n\n\n\n<p><strong>65. Give an example of the parameter in Web API.<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Parameters are used in Web API to determine the type of action you take on a particular resource. Each parameter consists of a name, value type and description that has the ability to influence the endpoint response.<\/p>\n\n\n\n<p>You can use the query API to get information about various entities within a data source.&nbsp;<\/p>\n\n\n\n<p>The Get Method employs multiple primitive parameters. For instance, the Get method needs id parameter to get product details \u2013<\/p>\n\n\n\n<p>public IHttpActionResult GetProductMaster(int id)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>ProductMaster productMaster = db.ProductMasters.Find(id);<\/p>\n\n\n\n<p>if (productMaster == null)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>return NotFound();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>return Ok(productMaster);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the same way, the Post method will require complex type parameters to post data to the server.<\/p>\n\n\n\n<p>public IHttpActionResult PostProductMaster(ProductMaster productMaster)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>if (!ModelState.IsValid)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>return BadRequest(ModelState);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>db.ProductMasters.Add(productMaster);<\/p>\n\n\n\n<p>db.SaveChanges();<\/p>\n\n\n\n<p>return CreatedAtRoute(\u201cDefaultApi\u201d, new { id = productMaster.id }, productMaster);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Similarly PUT method will require primitive data type example for id and complex parameter i.e. ProductMaster class.<\/p>\n\n\n\n<p>if (id != productMaster.id)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>return BadRequest();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>db.Entry(productMaster).State = EntityState.Modified;<\/p>\n\n\n\n<p>try<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>db.SaveChanges();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>catch (DbUpdateConcurrencyException)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>if (!ProductMasterExists(id))<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>return NotFound();<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>else<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>throw;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>66. Give an example to specify Web API Routing.&nbsp;<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Here is an example of Web API routing \u2013<\/p>\n\n\n\n<p>Config.Routes.MapHttpRoute(&nbsp;<\/p>\n\n\n\n<p>name: &#8220;MyRoute,&#8221;\/\/route name&nbsp;<\/p>\n\n\n\n<p>routeTemplate: &#8220;api\/{controller}\/{action}\/{id}&#8221;,\/\/as you can see &#8220;API&#8221; is at the beginning.&nbsp;<\/p>\n\n\n\n<p>defaults: new { id = RouteParameter.Optional }&nbsp;<\/p>\n\n\n\n<p>);&nbsp;<\/p>\n\n\n\n<p><strong>67. How to register an exception filter globally?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>You can use the following code to register an exception filter globally \u2013<\/p>\n\n\n\n<p>GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());&nbsp;&nbsp;<\/p>\n\n\n\n<p><strong>68. What are the different HTTP methods used in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Though there are a variety of HTTP verbs or methods, the most important and frequently used ones are GET, PUT, POST and DELETE.&nbsp;&nbsp;<\/p>\n\n\n\n<p>GET \u2013 It is used to retrieve information of the resource at a specified URI.<\/p>\n\n\n\n<p>PUT \u2013 The PUT method is used to update the values of a resource at a specified URI.<\/p>\n\n\n\n<p>POST \u2013POST method is used to create a new request and send data to the respective server.&nbsp;<\/p>\n\n\n\n<p>DELETE \u2013This method is used to remove the current resource at a specified URI.<\/p>\n\n\n\n<p>The functionality of these HTTP verbs can be summed up using the acronym CRUD in which each letter corresponds to different action \u2013<\/p>\n\n\n\n<p>C stands for Create or POST (creating data)<\/p>\n\n\n\n<p>R stands for Read or GET (data retrieval)<\/p>\n\n\n\n<p>U stands for Update or PUT (updating data)<\/p>\n\n\n\n<p>D stands for Delete or DELETE (deleting data)<\/p>\n\n\n\n<p>Other less frequently used HTTP verbs or methods as per the requirement include \u2013<\/p>\n\n\n\n<p>HEAD \u2013This method works the same way as the GET method and is primarily used to transfer the header section.<\/p>\n\n\n\n<p>OPTIONS \u2013This method helps identify and describe the communication option for a specific resource.<\/p>\n\n\n\n<p>CONNECT \u2013It is used to establish two-way communication between the server and the desired destination with the help of a given URI.&nbsp;<\/p>\n\n\n\n<p>TRACE \u2013 This method is used for diagnostic purposes to invoke a loop-back message along the target path and use that data for testing.&nbsp;<\/p>\n\n\n\n<p><strong>69. What is HttpConfiguration in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>HttpConfiguration refers to the global set of services used to override the behaviour of the default Web API. It has the following properties \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ParameterBindingRules<\/li>\n\n\n\n<li>Formatters<\/li>\n\n\n\n<li>MessageHandlers<\/li>\n\n\n\n<li>DependencyResolver&nbsp;<\/li>\n\n\n\n<li>Services&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>70. Explain the code snippet to show how we can return 404 errors from HttpError.<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Here\u2019s the Code for returning 404 error from HttpError \u2013&nbsp;<\/p>\n\n\n\n<p>string message = string.Format(\u201cTestCustomer id = {0} not found\u201d, customerid);<\/p>\n\n\n\n<p>return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);<\/p>\n\n\n\n<p><strong>71. What is the code used to register an exception filter from the action?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>One can register an exception filter using the following code \u2013<\/p>\n\n\n\n<p>[NotImplExceptionFilter]<\/p>\n\n\n\n<p>public TestCust GetMyTestCust (int custno)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>\/\/write the code<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>72. What are the testing tools or API for developing or testing web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>CFX<\/li>\n\n\n\n<li>Axis<\/li>\n\n\n\n<li>Jersey API&nbsp;<\/li>\n\n\n\n<li>Restlet&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>73. How can you pass multiple complex types in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Two ways to pass multiple complex types in Web API include \u2013 Newtonsoft array and using ArrayList.&nbsp;<\/p>\n\n\n\n<p><strong>74. What is the code for passing ArrayList in .NET Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>ArrayList paramList = new ArrayList();<\/p>\n\n\n\n<p>Category c = new Category { CategoryId = 1, CategoryName =\u201cMobilePhones\u201d};<\/p>\n\n\n\n<p>Product p = new Product { Productcode = 1, Name = \u201cMotoG\u201d, Price = 15500, CategoryID = 1 };<\/p>\n\n\n\n<p>paramList.Add(c);<\/p>\n\n\n\n<p>paramList.Add(p);<\/p>\n\n\n\n<p><strong>75. What is an HTTP status code?&nbsp;<\/strong><strong><\/strong><\/p>\n\n\n\n<p>HTTP status codes are three-digit integers issued by the server in response to the request made by the client, where each number specifies a meaning.&nbsp;<\/p>\n\n\n\n<p><strong>76. How are different HTTP Status Codes categorized?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>All HTTP status codes are categorized into five classes. These include \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>1xx (Informational) \u2013 It indicates that the server has received a certain request and the process is continuing.&nbsp;<\/li>\n\n\n\n<li>2xx (Successful)\u2013It indicates that the request was successful and accepted.&nbsp;<\/li>\n\n\n\n<li>3xx (Redirection)\u2013It indicates that the request has been redirected and its completion will require further action or steps.&nbsp;<\/li>\n\n\n\n<li>4xx (Client Error)\u2013It indicates that the request for the web page cannot be reached as either it is unavailable or has bad syntax.&nbsp;<\/li>\n\n\n\n<li>5xx (Server Error)\u2013It indicates that the server was unable to complete a certain request even though the request seems valid.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>77. What is the commonly observed HTTP response status code?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>There are many HTTP codes that are visible and others that are not visible at first but can be observed by the administrator using browser extensions or certain tools. Identifying and rectifying these errors is crucial to enhance the user experience and optimize search engine ranking over the web.&nbsp;&nbsp;<\/p>\n\n\n\n<p>Here are the most commonly seen HTTP status codes at a glance \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Status code 200 \u2013 request is ok.<\/li>\n\n\n\n<li>Status code 201 \u2013 Created&nbsp;<\/li>\n\n\n\n<li>Status code 202 \u2013 Accepted&nbsp;<\/li>\n\n\n\n<li>Status code 204 \u2013 No content&nbsp;<\/li>\n\n\n\n<li>Status code 301 \u2013 Moved permanently&nbsp;<\/li>\n\n\n\n<li>Status code 400 \u2013 Bad request&nbsp;<\/li>\n\n\n\n<li>Status code 401 \u2013 Unauthorized&nbsp;<\/li>\n\n\n\n<li>Status code 403 \u2013 Forbidden&nbsp;<\/li>\n\n\n\n<li>Status code 404 \u2013 Not found&nbsp;<\/li>\n\n\n\n<li>Status code 500 \u2013 Internal server error&nbsp;<\/li>\n\n\n\n<li>Status code 502 \u2013 Bad gateway&nbsp;<\/li>\n\n\n\n<li>Status code 503 \u2013 Service Unavailable&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>78. How do website owners avoid HTTP status codes?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>To ensure that the website is running smoothly and offers an optimal user experience, the administrator or website owner has to work consistently to keep automatically generated error codes to the minimum and also to identify 404 errors.&nbsp;<\/p>\n\n\n\n<p>The 404 HTTP status code can be avoided by redirecting users by a 301 code to an alternative location such as the start page. The bounce-back rate of website visitors can also be decreased with the manual creation of error pages.<\/p>\n\n\n\n<p><strong>79. Name method that validates all controls on a page?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Page.Validate() method system is executed to validate all controls on a page.<\/p>\n\n\n\n<p><strong>80. What is the use of DelegatingHandler?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>DelegatingHandler is a process used to develop a custom server-side HTTP message handler in ASI.Net Web API and chain message handlers together.<\/p>\n\n\n\n<p><strong>81. What do you mean by Internet Media Types?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Formerly known as the MIME type, it refers to the standard design for identifying content on the internet such as the type of information a piece of data contains.&nbsp;&nbsp;<\/p>\n\n\n\n<p>For example, if we receive a file over the email as an attachment, this identifier can be useful in knowing the media type of the attachment information contained in the header so that the browser can launch the appropriate plug-in.<\/p>\n\n\n\n<p>It is a good practice to know information on media types as every internet media type has to comply with the following format \u2013<\/p>\n\n\n\n<p>[type]\/[tree.] (Optional)[subtype][+suffix](Optional)[;parameters]<\/p>\n\n\n\n<p>Each media type must have the \u2018type\u2019 and the \u2018subtype\u2019 that indicates the type of information it contains. For instance,&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p><strong>Image<\/strong>\u2013 type\/png- subtype<\/p>\n\n\n\n<p><strong>Application<\/strong>\u2013 type\/rss- subtype+xml<\/p>\n\n\n\n<p><strong>82. Can a Web API return an HTML View?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Web API cannot return an HTML view. If you want to return views, it is best to use MVC.&nbsp;<\/p>\n\n\n\n<p><strong>83. What is the status code for \u201cEmpty return type\u201d in Web API?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>The status code 204 will return empty content in the response payload body.&nbsp;&nbsp;<\/p>\n\n\n\n<p><strong>84. Can you elaborate on different Web API filters?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Filters are used to add extra logic before or after specific stages of request processing within the Web API framework.&nbsp;<\/p>\n\n\n\n<p>There are different types of filters. Some built-in ones handle tasks such as authorization, response caching, etc. while custom filters can be created to handle concerns like error handling, authorization, etc.<\/p>\n\n\n\n<p>Filter run within the ASP.Net pipeline, also referred to as the filter pipeline and various types of filter depending on the execution at a particular stage in this filter pipeline include \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Authentication filter \u2013It helps to authenticate user details and HTTP requests.<\/li>\n\n\n\n<li>Authorization filter \u2013It runs before controller action to determine whether the user is authorized or not.&nbsp;<\/li>\n\n\n\n<li>Resource filter \u2013It runs after authorization and runs code before the rest of the filter pipeline. For example \u2013 OnResourceExecuted runs code after the rest of the pipeline gets completed.&nbsp;&nbsp;<\/li>\n\n\n\n<li>Action filter \u2013It is used to add extra logic before action gets executed and has the ability to change the result returned from a particular action.&nbsp;<\/li>\n\n\n\n<li>Exception filter \u2013It is used when controller action throws unhandled errors that occur before the response body is written.<\/li>\n\n\n\n<li>Override filter \u2013it is used to change the action methods or other filters.&nbsp;<\/li>\n\n\n\n<li>Result filter \u2013It runs code either before or after the execution of action results.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>85. What is the difference between ApiController and Controller?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>ApiController specializes in returning data arranged in series and sent to the client.<\/p>\n\n\n\n<p>public class TweetsController : ApiController<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ GET: \/Api\/Tweets\/&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public List&lt;Tweet&gt; Get()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Twitter.GetTweets();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Controller, on the other hand, provides normal views and handles HTTP requests.&nbsp;<\/p>\n\n\n\n<p>public class TweetsController : Controller<\/p>\n\n\n\n<p>{&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ GET: \/Tweets\/&nbsp; [HttpGet]&nbsp; public ActionResult Index()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p><strong>86. What is the difference between XML and JSON?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>XML is an acronym for eXtensible Markup Language and is designed to store and send data. JSON is an acronym for JavaScript Object Notation and is used to store and transfer data when data is sent from a server to a web page.<\/p>\n\n\n\n<p>Except for storing data in a specific format, XLM does not do much whereas JSON is a lightweight and easy to understand format for storing data, widely used in JavaScript.&nbsp;<\/p>\n\n\n\n<p><strong>87. What do you mean by Caching?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>Caching refers to the technique of storing data in temporary storage in a cache for future use. It keeps copies of all frequently used data and files in the cache, which enables the website to render faster. It also helps improve scalability so that the data can be directly retrieved from the memory when needed.<\/p>\n\n\n\n<p>The simplest cache in ASP.Net Web API is based on IMemoryCache.<\/p>\n\n\n\n<p>Some key advantages of Caching include \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Minimizes database hits<\/li>\n\n\n\n<li>Helps web pages render faster<\/li>\n\n\n\n<li>Reduces network costs<\/li>\n\n\n\n<li>Faster execution of process&nbsp;<\/li>\n\n\n\n<li>Highly efficient for both client and server<\/li>\n\n\n\n<li>Reduces load time on the server<\/li>\n\n\n\n<li>Best page management strategy to improve application\u2019s performance&nbsp;<\/li>\n<\/ul>\n\n\n\n<p><strong>88. What are the types of Caching?<\/strong><strong><\/strong><\/p>\n\n\n\n<p>There are different types of caching in ASP.NET Web API. These are \u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Page output caching \u2013This type of caching stores the recently used copy of the data in the memory cache to improve webpage performance. The cached output is fetched directly from the cache and sent to the application.<\/li>\n<\/ul>\n\n\n\n<p>Here\u2019s the code to implement page output caching \u2013<\/p>\n\n\n\n<p>&lt;%@ OutputCache Duration=&#8221;30&#8243; VaryByParam=&#8221;*&#8221; %&gt;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Page fragment caching \u2013In this form of caching, only fragments of data or web pages are cached instead of the entire page. It is helpful when the webpage contains dynamic and common sections and the user wants to cache some portions of it.&nbsp;<\/li>\n\n\n\n<li>Data caching \u2013In this form of caching, data is stored in temporary storage so that it can be retrieved later. Here is the syntax to store data using the Cache API \u2013<\/li>\n<\/ul>\n\n\n\n<p><strong>Cache[\u201ckey\u201d] = \u201cvalue\u201d;<\/strong><\/p>\n\n\n\n<p><strong>Web API FAQs<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>What is Web API and how it works?<\/strong><\/p>\n\n\n\n<p>A web API is an interface that allows you to access and manipulate data over the internet. It is typically used to access data from a web server, and can be used to create web applications or websites. It can be developed with the help of different technologies such as ASP.NET, or Java.<\/p>\n\n\n\n<p><strong>What is Web API in C# ?<\/strong><\/p>\n\n\n\n<p>A programming interface type that provides communication between software applications. It is often used to provide the interface for client applications and websites. It can also be used to access and save data from a database.<\/p>\n\n\n\n<p><strong>What are the types of API?<\/strong><\/p>\n\n\n\n<p>There are mainly four types of API used for web-applications. They are as follows:<br>\u2013 public,<br>\u2013 partner,<br>\u2013 private, and<br>\u2013 composite.<\/p>\n\n\n\n<p><strong>What is Web API example?<\/strong><\/p>\n\n\n\n<p>The full form of API is Application Programming Interface and it can extend the functionality of a web browser. An API would allow a third party such as Facebook to directly access the various functions of an external application, such as ordering a product on Amazon.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Why do we need Web API to develop RESTful services as we can also develop RESTful services using WCF?<\/strong><\/h5>\n\n\n\n<p>Yes, it is absolutely possible to develop RESTful services using WCF (Windows Communication Foundation). But there are few reasons why people are moving from WCF to WEB API for developing restful services. Some of them are as follows.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li>The Web API increases the TDD (Test Driven Development) approach in the development of RESTful services.<\/li>\n\n\n\n<li>If we want to develop RESTful services using WCF, then we need to do a lot of configuration settings, URI templates, contracts &amp; endpoints. WCF basically used to develop SOA (Service Oriented Architecture) based applications.<\/li>\n<\/ol>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What are the important return types supported in ASP.NET Web API?<\/strong><\/h5>\n\n\n\n<p>In ASP.NET Web API Application, the controller action methods can return the following:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li><strong>Void<\/strong>&nbsp;\u2013 It simply returns empty content<\/li>\n\n\n\n<li><strong>HttpResponseMessage<\/strong>&nbsp;\u2013 It will convert the response message to an HTTP message.<\/li>\n\n\n\n<li><strong>IHttpActionResult<\/strong>&nbsp;\u2013 It internally calls the ExecuteAsync method to create an HttpResponseMessage<\/li>\n\n\n\n<li><strong>Other types<\/strong>&nbsp;\u2013 You can also write the serialized return value into the response body. For example, you want to return Excel files.<\/li>\n<\/ol>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Which .NET framework supports Web API?<\/strong><\/h5>\n\n\n\n<p>The .NET Framework 4.0 and above version supports ASP.NET Web API.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Which protocol ASP.NET Web API supports?<\/strong><\/h5>\n\n\n\n<p>The ASP.NET Web App supports the one and only HTTP protocol.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>ASP.NET Web API uses which open-source library for JSON serialization?<\/strong><\/h5>\n\n\n\n<p>The ASP.NET Web API Framework uses the Json.NET library for JSON serialization.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>By default, Web API sends an HTTP response with which status code for an uncaught exception?<\/strong><\/h5>\n\n\n\n<p>It will send the response with HTTP Status 500 \u2013 Internal Server Error<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How do you construct HtmlResponseMessage in ASP.NET Web API?<\/strong><\/h5>\n\n\n\n<p><strong>public<\/strong> <strong>class<\/strong> HomeController : ApiController<\/p>\n\n\n\n<p><strong>{<\/strong><\/p>\n\n\n\n<p><strong>public<\/strong> HttpResponseMessage Get<strong>()<\/strong><\/p>\n\n\n\n<p><strong>{<\/strong><\/p>\n\n\n\n<p>HttpResponseMessage response = Request.CreateResponse<strong>(<\/strong>HttpStatusCode.OK, &#8220;value&#8221;<strong>)<\/strong>;<\/p>\n\n\n\n<p>response.Content = new StringContent<strong>(<\/strong>&#8220;Testing&#8221;, Encoding.Unicode<strong>)<\/strong>;<\/p>\n\n\n\n<p>response.Headers.CacheControl = new CacheControlHeaderValue<strong>()<\/strong><\/p>\n\n\n\n<p><strong>{<\/strong><\/p>\n\n\n\n<p>MaxAge = TimeSpan.FromMinutes<strong>(<\/strong>20<strong>)<\/strong><\/p>\n\n\n\n<p><strong>}<\/strong>;<\/p>\n\n\n\n<p><strong>return<\/strong> response;<\/p>\n\n\n\n<p><strong>}<\/strong><\/p>\n\n\n\n<p><strong>}<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Routing in ASP.NET Web API?<\/strong><\/h5>\n\n\n\n<p>The ASP.NET Web API Routing module is responsible for mapping the incoming HTTP requests to a particular controller action method. Based on the incoming requests the Web API uses URI and HTTP verbs to select the action method. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/routing-in-web-api\/\"><strong>Routing in ASP.NET Web API<\/strong>&nbsp;<\/a>article for more detail.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How the Web API Framework handle an incoming HTTP Request?<\/strong><\/h5>\n\n\n\n<p>When the ASP.NET Web API Framework receives an HTTP request, it tries to match the URI against one of the route templates available in the routing table. If no route template matches the URI, then Web API Framework returns a 404 error to the client who actually makes the request. Once a matching route is found in the Route Table, the Web API Framework then selects the controller and the action to be executed.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is SOAP?<\/strong><\/h5>\n\n\n\n<p>SOAP stands for Simple Object Access Protocol and it is an XML-based protocol. SOAP has specifications for both stateless and state-full implementation. It is also an XML-based messaging protocol for exchanging information among computers. The SOAP message consists of an envelope that includes SOAP headers and body to store the actual information we want to send. It supports different types of protocols such as HTTP, TCP, etc.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How Can we assign an alias name for ASP.NET Web API Action?<\/strong><\/h5>\n\n\n\n<p>We can give alias name for Web API action using the \u201cActionName\u201d attribute as follows:&nbsp;<\/p>\n\n\n\n<p><strong>[<\/strong>HttpPost<strong>]<\/strong><\/p>\n\n\n\n<p><strong>[<\/strong>ActionName<strong>(<\/strong>&#8220;StudentAdd&#8221;<strong>)]<\/strong><\/p>\n\n\n\n<p><strong>public<\/strong> <strong>void<\/strong> AddStudents<strong>(<\/strong>Student aStudent<strong>)<\/strong><\/p>\n\n\n\n<p><strong>{<\/strong><\/p>\n\n\n\n<p>StudentRepository.AddStudent<strong>(<\/strong>aStudent<strong>)<\/strong>;<\/p>\n\n\n\n<p><strong>}<\/strong><\/p>\n\n\n\n<p>For more detail about default naming convention and custom action names, please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/custom-action-names-in-web-api\/\"><strong>Custom Action Name<\/strong><\/a>&nbsp;article.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Content Negotiation in Web API?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. One of the standards of the REST service is that the client should have the ability to decide in which format they want the response \u2013 whether they want the response in XML or JSON etc. This is called&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/content-negotiation-web-api\/\"><strong>Content Negotiation in Web API<\/strong><\/a>. Web API Content Negotiation means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. That\u2019s why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/content-negotiation-web-api\/\"><strong>Web API Content Negotiation<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is CORS?<\/strong><\/h5>\n\n\n\n<p>Before understanding CORS, first, we need to understand the same-origin policy. Browsers allow a web page to make AJAX requests only within the same domain. The Browsers does not allow a web page from making AJAX requests to another domain. This is called the same-origin policy.<\/p>\n\n\n\n<p>CORS is a W3C standard that allows us to get away from the same-origin policy adopted by the browsers that restrict access from making AJAX requests from one domain to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use). Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/cross-origin-resource-sharing-web-api\/\"><strong>Cross-Origin Resource Sharing (CORS) in Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Web API Attribute Routing?<\/strong><\/h5>\n\n\n\n<p>The ASP.NET Web API 2 supports a new type of routing called attribute routing. Attribute routing means attributes are used to define routes. The Attribute routing provides more control over the URIs by defining routes directly on the actions and controllers. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/attribute-routing-in-web-api\/\"><strong>Attribute Routing in Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Why do we need Attribute Routing in Web API?<\/strong><\/h5>\n\n\n\n<p>The convention-based routing makes it hard to support certain URI patterns that are common in RESTful APIs. For example, resources often contain child resources such as Customers have orders, movies have actors, books have authors, etc. It\u2019s natural to create URIs that reflect these relations.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Authentication and Authorization in Web API?<\/strong><\/h5>\n\n\n\n<p>Once you create a Web API Service, then the most important thing that you need to take care of is security means you need to control access to your Web API Services.<\/p>\n\n\n\n<p>Authentication is the process of identifying the user. For example, one user let\u2019s say James logs in with his username and password, and the server uses his username and password to authenticate James.<\/p>\n\n\n\n<p>Authorization is the process of deciding whether the authenticated user is allowed to perform an action on a specific resource (Web API Resource) or not. For example, James (who is an authenticated user) has the permission to get a resource but does not have the permission to create a resource. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/authentication-and-authorization-in-web-api\/\"><strong>Authentication and Authorization in ASP.NET Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is an HTTP Message handler in ASP.NET Web API Application?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. An HTTP Message Handler in Web API is a class that receives an HTTP request and returns an HTTP response. The Message Handler is derived from the abstract HttpMessageHandler class. The HTTP Message handlers are good for cross-cutting concerns (such as authentication and authorization) that operate at the level of HTTP messages rather than controller actions. For example, a Custom HTTP Message handler might do the following things in a Web API Application.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li><strong>Read or modify the HTTP request headers.<\/strong><\/li>\n\n\n\n<li><strong>Add a response header to the HTTP response.<\/strong><\/li>\n\n\n\n<li><strong>Validate the requests before they reach the controller (i.e. Authentication and Authorization).<\/strong><\/li>\n<\/ol>\n\n\n\n<p>Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/http-message-handlers-in-web-api\/\"><strong>HTTP Message Handler in the Web API<\/strong>&nbsp;<\/a>article where we discussed this concept in detail with multiple real-time examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Why Web API versioning is required?<\/strong><\/h5>\n\n\n\n<p>Once you develop and deploy a Web API service then different clients start consuming your Web API services. As you know, day by day the business grows and once the business grows then the requirement may change, and once the requirement change then you may need to change the services as well, but the important thing you need to keep in mind is that you need to do the changes to the services in such a way that it should not break any existing client applications who already consuming your services.<\/p>\n\n\n\n<p>This is the ideal scenario when the Web API versioning plays an important role. You need to keep the existing services as it is so that the existing client applications will not break, they worked as it is, and you need to develop a new version of the Web API service which will start consuming by the new client applications. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/web-api-versioning-using-uri\/\"><strong>Web API Versioning<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What are the Different options available in Web API to maintain the versioning?<\/strong><\/h5>\n\n\n\n<p>The different options that are available to maintain versioning are as follows<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li>URI\u2019s<\/li>\n\n\n\n<li>Query String<\/li>\n\n\n\n<li>Version Header<\/li>\n\n\n\n<li>Accept Header<\/li>\n\n\n\n<li>Media Type<\/li>\n<\/ol>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What are Request Verbs or HTTP Verbs?<\/strong><\/h5>\n\n\n\n<p>In RESTful service, we can perform all types of CRUD (Create, Read, Update, Delete) Operation. In REST architecture, it is suggested to have a specific Request Verb or HTTP verb on the specific type of the call made to the server. Popular Request Verbs or HTTP Verbs are mentioned below:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li><strong>HTTP GET:<\/strong>&nbsp;This HTTP verb is Used to get the resource only.<\/li>\n\n\n\n<li><strong>HTTP POST:<\/strong>&nbsp;This HTTP verb is Used to create a new resource.<\/li>\n\n\n\n<li><strong>HTTP PUT:<\/strong>&nbsp;This HTTP verb is Used to update an existing resource.<\/li>\n\n\n\n<li><strong>HTTP PATCH:<\/strong>&nbsp;This HTTP verb is Used to update an existing resource.<\/li>\n\n\n\n<li><strong>HTTP DELETE:<\/strong>&nbsp;This HTTP verb is Used to Delete an existing resource.<\/li>\n<\/ol>\n\n\n\n<p><strong>Note:<\/strong>&nbsp;PUT and PATCH are not similar. If you are updating few columns in your database then use PATCG and if you are updating all the data then use PUT.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What do you mean by Parameter Binding in Web API?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The Parameter Binding means how the Web API Framework binds the incoming HTTP request data to the parameters of an action method of a Web API controller. The ASP.NET Web API action methods can take one or more parameters of different types. An action method parameter can be either of a complex type or primitive type. The Web API Framework binds the action method parameters either with the URL\u2019s query string or from the request body of the incoming HTTP Request based on the parameter type.<\/p>\n\n\n\n<p>By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string. And if the action method parameter type is a complex type then Web API Framework tries to get the value from the request body.<\/p>\n\n\n\n<p>But we can change this default behavior of the parameter binding process by using [FromBody] and [FromUri] attributes.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li><strong>FromBody<\/strong>: This will force the Web API Framework to get the value from the request body.<\/li>\n\n\n\n<li><strong>FromUri<\/strong>: This will force the Web API Framework to get the data from the URI (i.e. Route data or Query String)<\/li>\n<\/ol>\n\n\n\n<p>Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/parameter-binding-web-api\/\"><strong>Parameter Binding in ASP.NET Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is the use of Authorize Attribute?<\/strong><\/h5>\n\n\n\n<p>The ASP.NET Web API Framework provided a built-in authorization filter, i.e. Authorize Attribute. This filter checks whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How to Enable CORS in Web API?<\/strong><\/h5>\n\n\n\n<p>If we are going to consume the ASP.NET Web API Service using Jquery Ajax from another domain, then we need to enable CORS in the Web API application. Without enabling CORS, it is not possible to access the service from another domain using AJAX call. Enabling CORS in Web API is a two steps process.<\/p>\n\n\n\n<p><strong>Step1:&nbsp;<\/strong>Install&nbsp;<strong>Microsoft.AspNet.WebApi.Cors<\/strong>&nbsp;package.<\/p>\n\n\n\n<p><strong>Step2:&nbsp;<\/strong>Once you installed the&nbsp;<strong>Microsoft.AspNet.WebApi.Cors<\/strong>package then includes the following 2 lines of code in the&nbsp;<strong>Register()&nbsp;<\/strong>method of&nbsp;<strong>WebApiConfig&nbsp;<\/strong>class which is present inside the&nbsp;<strong>App_Start&nbsp;<\/strong>folder of your project.<\/p>\n\n\n\n<p><strong>EnableCorsAttribute&nbsp;cors =&nbsp;new&nbsp;EnableCorsAttribute(\u201c*\u201d,&nbsp;\u201c*\u201d,&nbsp;\u201c*\u201d);<\/strong><br><strong>config.EnableCors();<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Basic HTTP Authentication?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client needs to pass the username and password in the HTTP Authorization request headers. The credentials are formatted as the string \u201cusername:password: based encoded. Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/web-api-basic-authentication\/\"><strong>Basic Authentication in ASP.NET Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is ASP.Net identity?<\/strong><\/h5>\n\n\n\n<p>ASP.Net identity is the membership management framework given by Microsoft which can be easily integrated with ASP.NET Web API. This helps us in building a secure HTTP service.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is Token Based Authentication in Web API?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Nowadays, the use of Web API is increasing in a rapid manner. So as a developer we should know how to develop Web APIs. Only developing Web APIs is not enough if there is no security. So, it also very important to implement security for all types of clients (such as Browsers, Mobile Devices, Desktop applications, and IoTs) who are going to use our Web API services.<\/p>\n\n\n\n<p>The most preferred approach nowadays to secure the Web API resources is by authenticating the users in the Web API server by using the&nbsp;<strong>signed token<\/strong>&nbsp;(which contains enough information to identify a particular user) which needs to be sent to the server by the client in each and every request. This is called the&nbsp;<strong>Token-Based Authentication<\/strong>&nbsp;approach.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How does the Token-Based Authentication work?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. In order to understand how token-based authentication works, please have a look at the following diagram.<\/p>\n\n\n\n<p><strong>The Token-Based Authentication works as Follows:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li>The user enters his credentials (i.e. the username and password) into the client (here client means the browser or mobile devices, etc).<\/li>\n\n\n\n<li>The client then sends these credentials (i.e. username and password) to the Authorization Server.<\/li>\n\n\n\n<li>Then the Authorization Server authenticates the client credentials (i.e. username and password) and generates and returns an access token. This Access Token contains enough information to identify a user and also contains the token expiry time.<\/li>\n\n\n\n<li>The client application then includes the&nbsp;<strong>Access Token in the Authorization header<\/strong>&nbsp;of the HTTP request to access the restricted resources from the Resource Server until the token is expired.<\/li>\n<\/ol>\n\n\n\n<p>Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/token-based-authentication-web-api\/\"><strong>Token Based Authentication in Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is a Refresh Token?<\/strong><\/h5>\n\n\n\n<p>A&nbsp;<strong>Refresh Token<\/strong>&nbsp;is a special kind of token that can be used to obtain a new renewed access token that allows access to the protected resources. You can request the new access tokens by using the Refresh Token in Web API until the Refresh Token is blacklisted.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Why we need Refresh Token in Web API?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The idea of using the&nbsp;refresh token is to issue a short-lived access token (up to 30 minutes) for the first time and then&nbsp;use&nbsp;the refresh token to obtain a new access token and use that access token to access the protected resources.<\/p>\n\n\n\n<p>So, the user needs to provide the username and password along with the client info (i.e. the client id and client secret) to authenticate himself, and if the information provided by the user is valid, then a response contains a&nbsp;short-lived access token along with a&nbsp;long-lived refresh token gets generated.&nbsp;<\/p>\n\n\n\n<p>The refresh token is not an access token it is just an identifier for the access&nbsp;token<strong>.<\/strong>&nbsp;Now once the access token is expired, the user can&nbsp;use the refresh token to obtain another short-lived access token and so on.<\/p>\n\n\n\n<p>Please read our&nbsp;<a href=\"https:\/\/dotnettutorials.net\/lesson\/refresh-token-in-web-api\/\"><strong>Refresh Token in the Web API<\/strong><\/a>&nbsp;article where we discussed this concept in detail with examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>What is HMAC Authentication?<\/strong><\/h5>\n\n\n\n<p>This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The HMAC&nbsp;stands for&nbsp;Hash-based Message Authentication Code. From the full form of&nbsp;HMAC, we need to understand two things one is&nbsp;Message Authentication Code&nbsp;and the other one is&nbsp;Hash-Based. So HMAC is a mechanism that is used for creating a&nbsp;Message Authentication Code&nbsp;by using&nbsp;a&nbsp;Hash Function.<\/p>\n\n\n\n<p>The most important thing that we need to keep in mind is that while generating the&nbsp;Message Authentication Code using Hash Function&nbsp;we need to use a Shared&nbsp;Secret Key. Moreover, the Shared Secret Key must be shared between the Client and the Server involved in sending and receiving the data.&nbsp;<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Why do we need HMAC Authentication in Web API?<\/strong><\/h5>\n\n\n\n<p>The main uses of HMAC Authentication in Web API are as follows.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\" start=\"1\">\n<li><strong>Data integrity:<\/strong>&nbsp;It means the data sent by the client to the server has not tampered.<\/li>\n\n\n\n<li><strong>Request origination:<\/strong>&nbsp;The request comes to the server from a trusted client.<\/li>\n\n\n\n<li><strong>Not a replay request:<\/strong>&nbsp;The request is not captured by an intruder and being replayed.<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>1 What is Web API? Before we understand what is Web API, let&#8217;s see what is an API (Application Programing Interface). As per&nbsp;Wikipedia&#8217;s Definition of API: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications. To put it in simple terms, API [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[12,11],"tags":[],"class_list":["post-1816","post","type-post","status-publish","format-standard","hentry","category-asp-net","category-csharp"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"admin","author_link":"http:\/\/waqar-arshad.com\/index.php\/author\/waqar_29_1\/"},"uagb_comment_info":715,"uagb_excerpt":"1 What is Web API? Before we understand what is Web API, let&#8217;s see what is an API (Application Programing Interface). As per&nbsp;Wikipedia&#8217;s Definition of API: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications. To put it in simple terms, API&hellip;","_links":{"self":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1816","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/comments?post=1816"}],"version-history":[{"count":4,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1816\/revisions"}],"predecessor-version":[{"id":2154,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1816\/revisions\/2154"}],"wp:attachment":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/media?parent=1816"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/categories?post=1816"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/tags?post=1816"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}