[RESOLVED]enable CORS MVC 5

How to work with CORS?

Two ways:

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

Or 2. Adding the header through web.config:

<system.webServer>

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

..

Source:

http://www.c-sharpcorner.com/Blogs/11609/how-to-enable-cross-origin-resource-sharing-in-mvc.aspx

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

https://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API

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

http://blogs.msdn.com/b/webdev/archive/2013/07/02/manage-cors-policy-dynamically.aspx

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
explicitly.

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
AJAX
calls can use the
XMLHttpRequest
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.

Reference:

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

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