Have you ever come across the following error:
“Cross-origin Request Blocked. The same origin policy disallows reading the resource”.
Us to! It turns out, we get this error due to lack of CORS support while sharing resources. When we try to consume the Web API from origin A in a web application residing in origin B, we get the above error. To solve this error, we need to have a good understanding of CORS.
Although the purpose of this article is to learn the practical implementation of enabling CORS in the ASP.NET Web API, we will give a fair amount of weight to the theoretical concept also. CORS stands for Cross-Origin Resource-Sharing. For various security reasons user agents cannot share resources if they are not from the same origin. Various examples of user agents are browsers, HTML documents, scripts, and XMLHttpRequest.
Let us try to understand the concepts of Cross-Origin and Same-Origin. The concept of Origin was described by RF 6454. Two URLs would be called of the same origin, if they have:
- Scheme (http)
- Host (server)
- Port (8888)
The Origin consists of the Scheme, Host, and the Port number.
If two resources have the same combination of scheme, host, and port then they are considered of the same origin, else of the cross origin. Let us consider the following two URI
http://abc.com:80 and http://xyz.com:8080 are not of the same origin since their host and port are not the same. For the security reason resource sharing between these two URL may be restricted. Let us try to understand CORS with the example of XMLHttpRequest. We use the XMLHttpRequest to perform the HTTP operation on the server from the HTML document. There are two URLs used in the XMLHttpRequest:
- Requested URL or URL of the server
- URL of the document which initiated the request
If both URLs have the same scheme, host, and port then XMLHttpRequest object will perform the operation else it will block the HTTP operation for security reasons.
Both the server and the browser must have the support of the CORS. By default all recent browsers have CORS support, but as an API developer we need to enable support of CORS in the Web API.
CORS in ASP.NET Web API
Here we have created a very simple ASP.NET Web API which returns an array of classes as shown in the image below: