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”.
By default, the Solution Explorer looks like this.
Now, right-click on the project titled “ConsumeWebApiFromJquery” and select ADD --> ADD NEW ITEM --> HTML Page. Give the page a name as “Members.html”.
Switch to Members.html file and add the following code.
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta charset="utf-8" />
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
-
- $.ajax({
- type: "GET",
- url: "http://localhost:52044/api/member",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
-
-
- $("#MemberList").empty();
-
-
-
-
- console.log(response);
-
-
-
- var ListValue = "";
-
-
- var i;
-
-
- for (i = 0; i < response.length; ++i) {
- ListValue += "<li>" + response[i].MemberName + " --- " + response[i].PhoneNumber
- }
-
-
- $("#MemberList").append(ListValue);
- },
- failure: function (response) {
- alert(response.responseText);
- alert("Failure");
- },
- error: function (response) {
- alert(response);
- alert("Error");
- }
- });
- });
- </script>
- </head>
- <body>
-
- <h2>C-Sharpcorner Member List</h2>
-
- <!--Member List will appened here -->
- <ul id="MemberList">
-
- </ul>
-
- </body>
- </html>
Now, press F5 to execute the project.
You will encounter the following errors in Developer Tools.
ERROR 1
- OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed).
- 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.
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.
- <system.webServer>
- <httpProtocol>
- <customHeaders>
- <add name="Access-Control-Allow-Origin" value="*" />
- <add name="Access-Control-Allow-Headers" value="Content-Type, X-Your-Extra-Header-Key" />
- <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
- <add name="Access-Control-Allow-Credentials" value="true" />
- </customHeaders>
- </httpProtocol>
- </system.webServer>
Now, press F5 to execute the project again.
ERROR 2
- OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed)
- Failed to load http://localhost:52044/api/member: Response for preflight does not have HTTP ok status.
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.
- protected void Application_BeginRequest()
- {
- if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
- {
- Response.End();
- Response.Flush();
- }
- }
Now, you can see the developer tools in the output screen. You will get the perfect output in console log.
Now, you can see on the browser that your browser is ready with the following output.
OUTPUT