In this article, I am going to discuss how to enable Cross-Origin Resource Sharing in Web API which allows cross-domain AJAX calls. Please read our previous article before proceeding to this article as we are going to work with the same example. In our previous article, we discussed How to Call a Web API Service in a Cross-Domain Using jQuery AJAX with an example. The CORS support is released with ASP.NET Web API 2.
What are the same-origin policy and default behavior of browsers in AJAX Requests?
Browsers allow a web page to make AJAX requests only within the same domain. Browser security policy prevents a web page from making AJAX requests to another domain. This is called the same-origin policy. In other words, it is a known fact that browser security prevents a web page of one domain from executing AJAX calls on another domain.
What is CORS?
CORS is a W3C standard that allows you to get away from the same-origin policy adopted by the browsers to restrict access from one domain to resources belonging to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use).
Changes to Web API project:
Delete the following 2 lines of code in the Register() method of WebApiConfig class in WebApiConfig.cs file in the App_Start folder. We added these lines in our previous articles to make ASP.NET Web API Service return JSONP formatted data
Your WebApiConfig class should look as shown below.
How to enable CORS in Web API?
Step1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using the NuGet Package Manager Console. Step2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder
After adding the above two lines of code, the WebApiConfig class should as shown below.
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
Step3: In the Client Application, set the dataType option of the jQuery ajax function to JSON dataType: ‘json’
Now run the service first and then the client application and check everything is working as expected.
Parameters of EnableCorsAttribute
Origins: A comma-separated list of origins that are allowed to access the resource. For example “https://csharptechtics.blogspot.com, https://www.something.com” will only allow ajax calls from these 2 websites. All the others will be blocked. Use “*” to allow all
Headers: A 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 the null or empty string to allow none
Methods: A 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 a null or empty string to allow none
How to use EnableCors attribute at the Controller and action method level?
It is also possible to apply the EnableCors attribute either at the controller level or at the action method level. If applied at a controller level then it is applicable for all methods in that controller. Call the EnableCors() method without any parameter values.
Apply the EnableCorsAttribute on the controller class
In the same manner, we can also apply it at a method level if we wish to do so.
To disable CORS for a specific action apply [DisableCors] on that specific action.
Summary:
I Hope this post will be helpful to understand the concept of Cross-Origin Resource Sharing (CORS) in WEB API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
What are the same-origin policy and default behavior of browsers in AJAX Requests?
Browsers allow a web page to make AJAX requests only within the same domain. Browser security policy prevents a web page from making AJAX requests to another domain. This is called the same-origin policy. In other words, it is a known fact that browser security prevents a web page of one domain from executing AJAX calls on another domain.
What is CORS?
CORS is a W3C standard that allows you to get away from the same-origin policy adopted by the browsers to restrict access from one domain to resources belonging to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use).
Changes to Web API project:
Delete the following 2 lines of code in the Register() method of WebApiConfig class in WebApiConfig.cs file in the App_Start folder. We added these lines in our previous articles to make ASP.NET Web API Service return JSONP formatted data
var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter); config.Formatters.Insert(0, jsonpFormatter);
Your WebApiConfig class should look as shown below.
How to enable CORS in Web API?
Step1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using the NuGet Package Manager Console. Step2: 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();
After adding the above two lines of code, the WebApiConfig class should as shown below.
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(); } }
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();
Step3: In the Client Application, set the dataType option of the jQuery ajax function to JSON dataType: ‘json’
Now run the service first and then the client application and check everything is working as expected.
Parameters of EnableCorsAttribute
Origins: A comma-separated list of origins that are allowed to access the resource. For example “https://csharptechtics.blogspot.com, https://www.something.com” will only allow ajax calls from these 2 websites. All the others will be blocked. Use “*” to allow all
Headers: A 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 the null or empty string to allow none
Methods: A 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 a null or empty string to allow none
How to use EnableCors attribute at the Controller and action method level?
It is also possible to apply the EnableCors attribute either at the controller level or at the action method level. If applied at a controller level then it is applicable for all methods in that controller. Call the EnableCors() method without any parameter values.
Apply the EnableCorsAttribute on the controller class
[EnableCorsAttribute("*", "*", "*")] public class EmployeesController : ApiController { }
In the same manner, we can also apply it at a method level if we wish to do so.
public class EmployeeController : ApiController { [HttpGet] [EnableCorsAttribute("*", "*", "*")] public IEnumerable<employee> GetEmployees() { EmployeeDBContext dbContext = new EmployeeDBContext(); return dbContext.Employees.ToList(); } }
To disable CORS for a specific action apply [DisableCors] on that specific action.
Summary:
I Hope this post will be helpful to understand the concept of Cross-Origin Resource Sharing (CORS) in WEB API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.