Jan 15, 2014

Cross Origin Resource Sharing

Cross-origin resource sharing (CORS) works by letting server indicate which origins are allowed to call them. When browser make a request to other domain it sends along an origin in the request header with the value of domain from where its coming from. If the server allows CORS, it will send response with header Access-Control-Allow-Origin which indicates if call is allowed. If this header is not present the the browser will not allow javascript to receive the response. In addition to the origin, CORS let server indicate which HTTP methods are allowed. CORS doesn’t prevent the call from being invoked on the server; rather, it prevents the calling JavaScript from receiving the results. 

Request Header
Origin:http://localhost:55724

Response Header
Access-Control-Allow-Origin: http://localhost:55724

Web API 2 supports CORS via NuGet package Microsoft.AspNet.WebApi.Cors. Here is how you can enable CORS for your api. This can done globally or at the controller level or at the action level.
 
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //var cors = new EnableCorsAttribute("*", "*", "GET");
            config.EnableCors();
    
    
  [EnableCors("http://localhost:55725", "*", "GET")]
  public class ProductController : ApiController

Preflight Requests
For some CORS requests, the browser sends an additional request, called a “preflight request”, before it sends the actual request for the resource. The pre-flight request uses the HTTP OPTIONS method. If the preflight request succeeds, the browser sends the actual request.

No comments:

Post a Comment