How to work with CORS?

Two ways:

1. Adding: HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

Or 2. Adding the header through web.config:


        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />




However, as a side note, you might also be interested in looking at:  CORS support for WebAPI:


CORS attributes (EnableCors) dynamically (i.e., at controller level):


Thank you. It works. What does it mean when I enable CORS?

Hi Alex,

CORS means Cross Origin Resource Sharing. It allows the communication across domains. By enabling it for our server APIs – we allow our services to have communications across the domains. By default browsers will not allow it, unless we pass set http header

CORS allows you to request data from another origin while message passing between main window and an iframe is used when you want to communicate with an app that is inside the iframe but is not in the same origin.

A practical example:

1.You have an iframe that has a youtube player.

2.You request some videos to play from youtube data api (CORS, could be JSONP, XHR or whatever).

3.You now pass a cross-domain message to the iframe to start playing any of the video you requested in step #2.

From Reference: http://stackoverflow.com/a/8186722

Also from WikiPedia definition:

Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a
web page to be requested from another
domain outside the domain from which the resource originated.[1]
In particular, JavaScript’s
calls can use the
mechanism. Such "cross-domain" requests would otherwise be forbidden by

web browsers
, per the
same-origin security policy
. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request.[2]
It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.



It also means you need to take extra care with security, as you have disabled the browsers security. You will be open to cross site scripting attacks unless you code for them.

Leave a Reply