Loading

ASP.NET Web API

What is Cross-Origin Resource Sharing in Web API?. The Complete ASP.NET Web API Developer Course 2022 [Videos].

In this Video, I am going to discuss how to enable Cross-Origin Resource Sharing in Web API which allows cross-domain AJAX calls. Please watch our previous Video before proceeding to this Video as we are going to work with the same example. In our previous Video, 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.

  1. What are the same-origin policy and default behavior of browsers in AJAX Requests?
  2. What is CORS?
  3. How to enable CORS in Web API?
  4. Understanding the Parameters of EnableCorsAttribute.
  5. How to use the EnableCors attribute at the Controller and action method level?
  6. How to Disable CORS?
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 Videos 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.

Cross-Origin Resource Sharing in Web API

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(cors);

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(cors);
}
}

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(cors);

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://www.dotnettutorials.net, 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 the 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.

See All

Comments (322 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /322

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /322

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /322