In modern web applications developers mostly use any client side frameworks like AngularJS, EmberJS, Knockout etc. and in order to make server-side request they either call a Web API or a web service through XMLHttpRequest object and perform CRUD operations.
XHR or XMLHttpRequest in an API available to web browser scripting languages like javascript to send HTTP request to a webserver and load the server response data back in the script. Due to some security reasons these requests are allowed only if both server and the application making that request have same protocol, domain and port values.
So for example if the application URL is http://localhost/WebApplication and it is calling http://localhost:8089/WebService it will fail and give cross-origin request issue.
In internet explorer it ignores the port no. so if both are on localhost or same base address it will call it without any issue. But this does not solve the case. In order to develop a service or a Web Api that has to be accessed by any client we need to handle it properly.
In this post, I will show how simply with few steps we can enable Cross Origin Resource sharing in ASP.NET Web Api.
- First of all in your Web API project add a NuGet Package “Microsoft.AspNet.WebApi.Cors” through NuGet Package Manager

- Then in the WebApiConfig.cs class add an entry to enable cors.

- And finally add the EnableCors attribute on Controller and specify the allowed origins, headers and methods

- You can set origin, header and methods as below.

Hope this helps!
Like this:
Like Loading...