Enabling Cross Origin Request Sharing in ASP.Net Web API

Introduction

This article explains Cross Origin Request Sharing and how to enable it in our ASP.NET Web API application.

Introduction about CORS

Cross Origin Resource Sharing (CORS) allows the server to serve a resource to the permitted origin domains. It is used for defining the way by which the server and browser can interact and whether or not cross origin requests are allowed. It is a W3C standard.

Here we create two projects. The first one is "CrosEnable" that hosts the Web API controller. And the second is "ClienApp" that invokes the web services. Each application is hosted in a different domain. An AJAX request from "ClientApp" to "CorsEnable" is called the cross-origin request.

chk12.jpg

Creating the Web API project to enable the CORS

Step 1

To create the web application:

  • Start Visual Studio 2012.
  • Click on "New Project", select "template" -> "Visual C#" -> "Web".
  • Choose "ASP.NET MVC Application4" and change the name of the application.
  • Click onthe "OK" button.

    chk10.jpg

  • From the new ASP.NET MVC4 Project:

    chk11.jpg

  • Select the "Basic" .
  • Click on the "OK" button.

Step 2

Create a controller class "CheckController.cs".

  • In the "Solution Explorer".
  • Right-click on the "Controller Folder" -> "Add" -> "Controller".
  • Change the name and select the "Empty API controller" from the Template.

    chk13.jpg

  • Click on the "OK" button.

Write this code in the "CheckController.cs" class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Web.Cors;  
  8. {  
  9.     public class CheckController : ApiController  
  10.     {  
  11.         public HttpResponseMessage Get()  
  12.         {  
  13.             return new HttpResponseMessage()  
  14.             {  
  15.                 Content = new StringContent("GET: Check new Message")  
  16.             };  
  17.         }  
  18.         public HttpResponseMessage Post()  
  19.         {  
  20.             return new HttpResponseMessage()  
  21.             {  
  22.                 Content = new StringContent("POST:  Check new Message")  
  23.             };  
  24.         }  
  25.         public HttpResponseMessage Put()  
  26.         {  
  27.             return new HttpResponseMessage()  
  28.             {  
  29.                 Content = new StringContent("PUT:  Check new Message")  
  30.             };  
  31.         }  
  32.     }  
  33. }   

Step 3

Now execute the application; press F5. Then navigate to the URL http://localhost:44854/api/check. It looks likes this:

output.jpg

Step 4

Now add another "MVC4 application project" with the "Basic" project template.

  • In the "Solution Explorer".
  • Right-click on the "Solution'CorsEnable'(Project 1)" then select "Add" -> "New Project".
  • Select MVC4 web application with "Basic" template.

Step 5

Create the controller class in the second project using the following:

  • In the "Solution Explorer".
  • Right-click on the "Controller Folder" then select "Add" -> "Controller".
  • Change the name and select the "Empty MVC controller" from the Template.

    chk14.jpg

  • Click on the "OK" button.

Now "Right-click" on the "Index method" and click on "View Index".

chk1.jpg

There is open a window without perform any changes click on "OK" button. Open the "index.cshtml" and write this code.

chk2.jpg

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. <h2>Test Methods</h2>  
  5. <div>  
  6.     <select id="method">  
  7.         <option value="get">GET</option>  
  8.         <option value="post">POST</option>  
  9.         <option value="put">PUT</option>  
  10.     </select>  
  11.     <input type="button" value="Click Me" onclick="sendRequest()" />  
  12.     <span id='value1'>(Output)</span>  
  13. </div>  
  14. @section scripts {  
  15. <script>  
  16.     var serviceUrl = 'http://localhost:44854/api/check'; // Replace with your URI.  
  17.     function sendRequest() {  
  18.         var method = $('#method').val();  
  19.         $.ajax({  
  20.             type: method,  
  21.             url: serviceUrl  
  22.         }).done(function (data) {  
  23.             $('#value1').text(data);  
  24.         }).error(function (jqXHR, textStatus, errorThrown) {  
  25.             $('#value1').text(jqXHR.responseText || textStatus);  
  26.         });  
  27.     }  
  28. </script>  
  29. }

Step 6

Now again execute the project "ClientApp". It looks like this:

chk3.jpg

Then click on the "Click Me" button. Then it shows this output.

chk4.jpg

Step 7

Now enable the Cross Origin Request Sharing (CORS).

First we install the "Microsoft.ASPNet.WebApi.Cros".

  • Go to the Tools menu.
  • Select "Library Package Manager" -> "Package Manager Console".
  • Write this command "PM> Install-Package Microsoft.AspNet.WebApi.Cors.ko -Pre".

In the "ClientApp", open the WebAPIConfig file as in the following:

  • In the "Solution Explorer".
  • In the "App_Start" -> "WebApiConfig.cs" add the following code. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. namespace ClientApp  
  6. {  
  7.     public static class WebApiConfig  
  8.     {  
  9.         public static void Register(HttpConfiguration config)  
  10.         {  
  11.             config.EnableCors();  
  12.             config.Routes.MapHttpRoute(  
  13.                 name: "DefaultApi",  
  14.                 routeTemplate: "api/{controller}/{id}",  
  15.                 defaults: new { id = RouteParameter.Optional }  
  16.             );  
  17.         }  
  18.     }  
  19. }   

Step 8

In the Check Controller We add this line of code for enabling the CORS.

  [EnableCors(origins: "http://localhost:44854", headers: "*", methods: "*")]

Use these namespaces.

 

  1. using System.Web.Cors;  
  2. using System.Web.Http.Cors;  

 

Step 9

Now to execute the application press F5. The output is like this.

 chk6.jpg

Select the Get Method and click on the button.

chk7.jpg

Select the Post Method and click on the button.

chk8.jpg

Select the Put Method and click on the button.

chk9.jpg


Similar Articles