Some time ago I wrote a post about how to enable CORS in a web API. Now, CORS may be easy, but if you do not pay attention it will still cause some silly errors that can make you loose an absurd amount of time due to some very uninformative message errors. Errors like this one:

jquery-3.3.1.js:9600 Access to XMLHttpRequest at ‘localhost:51684/api/Students/GetStudents’ from origin ‘xxx’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I encountered this error not long time ago. My team was developing a project that involved a web API, and a web client. When we tested it locally we had two domains:

  • A web API: localhost:51684/
  • An Net.MVC project:localhost:51779

When we tried to access the API from the Net.MVC we got  a Cross origin error.
The devilish thing about that, is that we had CORS enabled – or so we thought. The error mislead us into thinking we had done something wrong in the Web Api configuration, and it took us some time to realize that we were looking for the bug in the wrong place … or project as it turned out it was the case.

Let´s imagine we have a Web API  like, for example, the one described in this post about adding Web APi support to existing ASP.NET MVC projects. That API had a GetStudents method to return a list of students  that could be accessed at   localhost:51684/api/Students/GetStudents. We decide to enable CORS for that API and add these lines to the web.config just before the system.webServer closing tag.
Let´s imagine also that a different project wants to access that API; it may be an ASP.NET MVC project, an ionic browser emulator, etc it does not matter: as long as we have two different domains we need to work with CORS. For this example we will use a ASP.NET MVC project, with a simple button that uses jquery to make a petition to the Students API. Something like this:

$.get("localhost:51684/api/Students/GetStudents", function (data, status) {
alert("Status: " + status);
});

when we clicked the button and a request is send to the Students API we will get this error Access to XMLHttpRequest at ‘localhost:51684/api/Students/GetStudents’ from origin ‘xxx’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Can you see where is the problem? CORS is correctly enabled in the Web API Project, but there is a very easy to miss bug in the javascript request of the ASP.NET MVC project. It should be like this:

$.get("http://localhost:51684/api/Students/GetStudents", function (data, status) {
alert("Status: " + status);
});

Correcting that will make tis particular CORS error will go away 🙂