No Access-Control-Allow-Origin header is present on the requested resource

If you’re facing No 'Access-Control-Allow-Origin' header is present on the requested resource while making AJAX request from you’re client to server this article is for you. First understand what is No 'Access-Control-Allow-Origin'.

According to W3C same-origin policy restrictions imposed by browsers that your java Script only make Ajax call backs to same origin. For example an Ajax call from www.foo.com can’t send request to www.foo2.com

CORS rule implemented by browser but its implementation configure on server. Web API 2 provide you facilities so that you can configure policy to allow java Script clients to access you’re API from different origin.

Whenever you see an error in your browser window like this one No 'Access-Control-Allow-Origin' header is present on the requested resource you need to follow below instructions.

Steps to eliminate error No 'Access-Control-Allow-Origin'

Install this NuGet package

Microsoft.AspNet.WebApi.Cors

Now in your web API configuration file add this line of code at the start of Register method.

     config.EnableCors();
     

Remember that this enable CORS globally in your application. If you want to enable CORS specifically on a controller you need to decorate your controller with below code.

    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]

Thanks for reading
Good luck.