Consuming ASP.NET Web API Using jQuery - Part Three

In this article you will come know to about How to consume / use Web API in Asp.Net MVC step by step.

In this article, you will learn how to consume/use Web API in ASP.NET MVC step by step.

This article is the third part of my ASP.NET MVC Web API series.

Consuming Web API From jQuery

In this article, we have used localhost Web API and called for the GET request. The following is the process:

  • Create ASP.NET MVC Project.
  • Add an HTML file called Members.html file.
  • Write GET call of for jQuery AJAX to fetch the data from ASP.NET Web API.
  • System or process will throw two different errors.
  • Resolve the errors with the solution given in this article.
  • Run the project and check the output.

Step by Step Implementation

Create an new ASP.NET Empty Website project called “ConsumeWebApiFromJquery”.

Consuming ASP.NET Web API From jQuery

By default, the Solution Explorer looks like this.

Consuming ASP.NET Web API From jQuery

Now, right-click on the project titled “ConsumeWebApiFromJquery”  and select ADD --> ADD NEW ITEM --> HTML Page. Give the page a name as “Members.html”.

Consuming ASP.NET Web API From jQuery

Switch to Members.html file and add the following code.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  7.     <script type="text/javascript">  
  8.         $(document).ready(function () {  
  9.              
  10.                 $.ajax({  
  11.                     type: "GET",  
  12.                     url: "http://localhost:52044/api/member",  
  13.                     contentType: "application/json; charset=utf-8",  
  14.                     dataType: "json",  
  15.                     success: function (response) {  
  16.   
  17.                         //Clear all previous list of members  
  18.                         $("#MemberList").empty();  
  19.   
  20.                         //Display Asp.Net Web API response in console log   
  21.                         //You can see console log value in developer tool   
  22.                         //by pressing F12 function key.  
  23.                         console.log(response);  
  24.   
  25.   
  26.                         // Variable created to store <li>Memeber Detail</li>  
  27.                         var ListValue = "";  
  28.   
  29.                         //Variable created to iterate the json array values.  
  30.                         var i;  
  31.   
  32.                         //Generic loop to iterate the response arrays.  
  33.                         for (i = 0; i < response.length; ++i) {  
  34.                             ListValue += "<li>" + response[i].MemberName + " --- " + response[i].PhoneNumber  
  35.                         }  
  36.   
  37.                         //Add/Append the formatted values of ListValue variable into ID called "MemberList"  
  38.                         $("#MemberList").append(ListValue);  
  39.                     },  
  40.                     failure: function (response) {  
  41.                         alert(response.responseText);  
  42.                         alert("Failure");  
  43.                     },  
  44.                     error: function (response) {  
  45.                         alert(response);  
  46.                         alert("Error");  
  47.                     }  
  48.                 });  
  49.         });  
  50.     </script>  
  51. </head>  
  52. <body>  
  53.   
  54.     <h2>C-Sharpcorner Member List</h2>  
  55.       
  56.     <!--Member List will appened here -->  
  57.     <ul id="MemberList">  
  58.   
  59.     </ul>  
  60.   
  61. </body>  
  62. </html>  

Now, press F5 to execute the project.

You will encounter the following errors in Developer Tools.

ERROR 1

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed).
  2. Response to the preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50702' is therefore not allowed access.
Consuming ASP.NET Web API From jQuery

To remove the above errors, the Web.Config file needs to be updated.

Update Web.Config file of your WebAPI Project with the following codes.

  1. <system.webServer>  
  2.   <httpProtocol>  
  3.     <customHeaders>  
  4.       <add name="Access-Control-Allow-Origin" value="*" />  
  5.       <add name="Access-Control-Allow-Headers" value="Content-Type, X-Your-Extra-Header-Key" />  
  6.       <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />  
  7.       <add name="Access-Control-Allow-Credentials" value="true" />  
  8.     </customHeaders>  
  9.   </httpProtocol>  
  10. </system.webServer>  

Now, press F5 to execute the project again.

ERROR 2

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed)
  1. Failed to load http://localhost:52044/api/member: Response for preflight does not have HTTP ok status.
Consuming ASP.NET Web API From jQuery

To remove the above errors, the Global.asax.cs file needs to be updated. Update the Global.asax.cs file of your WebAPI Project with the following codes.

  1. protected void Application_BeginRequest()  
  2.         {  
  3.             if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")  
  4.             {  
  5.                 Response.End();  
  6.                 Response.Flush();  
  7.             }  
  8.         }  

Now, you can see the developer tools in the output screen. You will get the perfect output in console log.

Consuming ASP.NET Web API From jQuery

Now, you can see on the browser that your browser is ready with the following output.

OUTPUT

Consuming ASP.NET Web API From jQuery