How CORS works

Cross-origin resource sharing design presents various HTTP headers, such as Origin and Access-Control-Allow-Origin. These headers will be set by a browser for cross-origin requests, if it supports CORS.

Let's try to access the following Web API method that is not configured to support CORS:

// GET: api/Contacts/id
public Contact Get(int id)
{
      return contacts.FirstOrDefault(x => x.Id == id);
}

Accessing this method from a different domain will lead to the following error:

XMLHttpRequest cannot load http://localhost:53858/api/contacts/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53870' is therefore not allowed access. 

We need to pass some special headers such as Origin header ...

Get ASP.NET Web API Security Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.