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 sentitive data from another site. However, sometimes you might want to let other sites call your web API. 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. It’s important to understand that same-origin policy does not prevent the browser from sending the request. Instead, it prevents the application from seeing the response.
To enable CORS in Web API install the core nuget package
In App_Start inside WebApiConfig.cs class add following where config is HttpConfiguration.
On the Controller action u can use the
add following namespace to your controller
this allows CORS request coming only from http://mytechnetknowhows.azurewebsites.net.
If the server allows the request, it sets the Access-Control-Allow-Origin header. The value of this header either matches the Origin header, or is the wildcard value *, meaning that any origin is allowed.
If the response does not include the Access-Control-Allow-Origin header, the AJAX request fails. Specifically, the browser disallows the request. Even if the server returns a successful response, the browser does not make the response available to the client application.
Scope Rules for [EnableCors] – You can enable CORS per action, per controller, or globally for all Web API controllers in your application. If you set the attribute at more than one scope, the order of precedence is: Action, Controller, Global.
Passing Credentials in Cross-Origin Requests – Credentials require special handling in a CORS request. By default, the browser does not send any credentials with a cross-origin request. Credentials include cookies as well as HTTP authentication schemes. To send credentials with a cross-origin request, the client must set XMLHttpRequest.withCredentials to true. In addition, the server must allow the credentials.
To allow cross-origin credentials in Web API, set the SupportsCredentials property to true on the [EnableCors] attribute.