Cross Origin Sharing In Web API

In this article, I am going to demonstrate how we can enable CORS in Web API service. I am going to create a Web API service which returns some in-memory array objects, and will create another project called Web Client to access the service.

What is Same and Different Origin?

Two URLs have the same origin if they have identical schemes, hosts, and ports.
These two URLs have the same origin,

  • http://RKSite.com/Index.html
  • http://RKSite.com/Home.html

These URLs have different origins than the previous two,

  • http://RKSite.net - Different domain
  • http://RKSite.com:9000/Index.html - Different port
  • https://RKSite.com/Index.html - Different scheme
  • http://www.RKSite.com/Index.html - Different subdomain

Steps to create the solution

  1. Create an ASP.NET Web API Project.





  2. Add Customer class to the Models folder and add the below properties to store in-memory data.





  3. Add Controller and update the below code.





    Here, the Web API consists of nly 4 options to do the operation, GET, POST ,PUT, and Delete. I have created Customer array object and in GET method, I am returning that value.



  4. Execute the project and browse the Controller. You can see the customer details in xml format as we are browsing in Chrome browser. If we access same URL in Internet Explorer, it will return in JSON format.


  5. Create Empty Web project to access the service.





  6. Add RKHome html page to bind the service data.



    Here, I have added button and paragraph tags to get and bind the service details. On button click, I am trying to fetch the Customer details from service URL, using AJAX call.
    1. // AJAX call to get the data from the webapi url service  
    2. $.get(url).always(showResponse);  

    The above $.get function internally uses AJAX call to fetch the data.



  7. Execute the WebClient project and browse the RKHome html page.

    Here, on button click, we are getting error message because the service is not giving access to the client project as both are in different origins.

    If we need to give access, first we need to enable CORS in service and enable WebClient project URL in Service Web API config file.



  8. Add CORS from Manage NuGet packages.





  9. Add the below code in WebApiConfig.cs file to enable CORS for WebClient project.



  10. Execute the WebClient project again and browse the RKHome page. Now, on button click, the service is fetching the records as we enable the CORS for this client. Here, I am just binding the JSON data to the client. We can modify or design the data in required format and design.


Hope this article helps you in understanding the CORS in ASP.NET Web API. Please leave your comments to improve the articles.

Up Next
    Ebook Download
    View all
    Learn
    View all