Introduction
Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.Cross Origin Resource Sharing (CORS)
Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than other techniques.
Enable CORS
- Install-Package Microsoft.AspNet.WebApi.Cors
- Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:
Scope Rules for [EnableCors]
- Per Action
- Per Controller
- Globally
Per Action
To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.
Per Controller
If you set [EnableCors] on the controller class, it applies to all the actions on the controller. To disable CORS for an action, add the [DisableCors] attribute to the action. The following example enables CORS for every method except PutItem.
Tags
Asp.Net Web Api