Cross-origin resource sharing (CORS) is a browser control that prevents the use of a foreign server's resources on a site without the resource origin's permission. CORS exists to prevent resources that your server hosts from being embedded on other websites. Most modern browsers require certain HTTP headers to be sent with a response that a server sends. If the hosts are different, or it will reject the data it sends back. Keep in mind, however, that CORS is a browser control, and the user's browser is not necessarily required to enforce any CORS policy. Enabling this feature informs browsers that access the API what the rules for resource sharing are (specifically, in the HTTP headers), and the browser determines if those rules conform to its policy.
CORS is configured in the customHeaders element of the web.config file. If you do not intend to share the API publicly, set the Access-Control-Allow-Origin key's value to whatever your front-end host's domain is. The configuration of CORS is only required if you intend to allow cross-domain requests, such as in the following scenarios:
-
The API is hosted on a different domain, subdomain, or host than the client, including if:
-
The API is accessed by an IP address, but the client is accessed by a domain or hostname (for example, 120.120.120.10 and example.com, respectively).
-
The API is accessed from a different domain or subdomain (for example, public-access.example.com and example.com, or even www.example.com and example.com).
-
The API is accessed from a different IP address from the client (for example, 120.120.120.10 and 120.120.120.11).
-
The connection protocol for the API and the client differ (http and https).
-
-
You intend to develop an application that obeys the CORS standard against the API and still use the standard client or another application that obeys the standard.
-
You intend to allow others to develop an application that obeys the CORS standard against the API.
CORS is, as aforementioned, a browser control, and as such is not always consistently implemented. In some browsers, a change in protocol is enough to activate CORS; in others, the subdomain or domain name have to be different.
For more information on configuring CORS to allow access from a single external domain hosting the front-end client, see Allowing CORS from a Foreign Domain.
Alternatively, for information on configuring CORS to host the API as an externally available service, see Allowing CORS from All Domains.
Unfortunately, allowing cross-origin resource sharing for multiple hosts can only be enabled by allowing it for all domains. There is no standard regarding allowing multiple, specific domains and it is not supported.