Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Cross-origin resource sharing ASP.NET Web API

Suggested Videos
Part 12 - FromBody and FromUri in Web API
Part 13 - Call ASP.NET Web API from jQuery
Part 14 - Calling ASP.NET Web API service in a cross domain using jQuery ajax

In this video we will discuss how to call an ASP.NET Web API service in a cross domain using jQuery ajax. In our previous video we discussed how to do this using JSONP. In this video we will discuss how to enable CORS (Cross Origin Resource Sharing) which allows cross domain ajax calls. CORS support is released with ASP.NET Web API 2.

This is continuation to Part 14. Please watch Part 14 from ASP.NET Web API tutorial before proceeding with this video.



Comment the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder. We added these lines in our previous video to make ASP.NET Web API Service return JSONP formatted data
//var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
//config.Formatters.Insert(0, jsonpFormatter);

To allow cross domain ajax calls by enabling CORS
Step 1 : Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using NuGet Package Manager Console. Make sure to select "EmployeeService" project from "Default project" dropdown.
Install-Package Microsoft.AspNet.WebApi.Cors

install cors web api



Step 2 : Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors();

Step 3 : In the ClientApplication, set the dataType option of the jQuery ajax function to json
dataType: 'json'

Parameters of EnableCorsAttribute
Parameter Description
origins Comma-separated list of origins that are allowed to access the resource. For example "http://www.pragimtech.com,http://www.mywebsite.com" will only allow ajax calls from these 2 websites. All the others will be blocked. Use "*" to allow all
headers Comma-separated list of headers that are supported by the resource. For example "accept,content-type,origin" will only allow these 3 headers. Use "*" to allow all. Use null or empty string to allow none
methods Comma-separated list of methods that are supported by the resource. For example "GET,POST" only allows Get and Post and blocks the rest of the methods. Use "*" to allow all. Use null or empty string to allow none

The following 2 lines of code in Register() method of WebApiConfig.cs file in App_Start folder, enables CORS globally for the entire application i.e for all controllers and action methods

EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");
config.EnableCors();

EnableCors attribute can be applied on a specific controller or controller method. 

If applied at a controller level then it is applicable for all methods in the controller. To apply it at the controller level

1. There is no need to create an instance of EnableCorsAttribute in Register() method of WebApiConfig.cs file. Call the EnableCors() method without any parameter values.

config.EnableCors();


2. Apply the  EnableCorsAttribute on the controller class
[EnableCorsAttribute("*", "*", "*")]
public class EmployeesController : ApiController
{
}

In the same manner, you can also apply it at a method level if you wish to do so.

To disable CORS for a specific action apply [DisableCors] on that specific action

When CORS is enabled, the browser sets the origin header of the request to the domain of the site making the request. The server sets Access-Control-Allow-Origin header in the response to either * or the origin that made the request. * indicates any site is allowed to make the request.

ASP.NET Web API tutorial for beginners

13 comments:

  1. EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);

    ReplyDelete
    Replies
    1. Exactly. i faced the same issue, cors enabled but not working and i saw your post it was really helpful. Thanks!

      Delete
  2. Hi cors is not installing in framework 4.0.

    ReplyDelete
  3. After Enabling cors in WebConfig I am still getting the cross origin error

    ReplyDelete
    Replies
    1. Cors feature only included in .net 4.5 and web api2

      Delete
    2. Pass the 'cors' to EnableCors method.
      config.EnableCors(cors);

      Delete
    3. Restart visual studio,rebuild solution once and then check it will work.

      Delete
    4. Yes Lingaswamy M, In above text tutorial, cors object has forgotten to pass in config.EnableCors() method.

      Question correction: please read word 'WebAbiconfig' in place of 'WebConfig'.

      Delete
  4. I have hosted my webapi on my register domain and when I send post request from my xamarin app using visual studio it give error no compitable code is running but same thing I do from postman it works fine. So what is the solution of this problem
    Thanks

    ReplyDelete
  5. Yep Not able to Call.CORS Issue-Access to XMLHttpRequest at 'http://localhost:52498/WebAPIandSQLServer/api/Employees' from origin 'http://localhost:55566' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    ReplyDelete
    Replies
    1. I could get it work with the follwing too..
      var response = Request.CreateResponse(HttpStatusCode.OK,
      entities.Employees.ToList());
      response.Headers.Add("Access-Control-Allow-Origin", "*");
      return response;

      Delete
  6. but add [EnableCorsAttribute("*", "*", "*")] in method level is working

    ReplyDelete

It would be great if you can help share these free resources