• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Thursday, April 23, 2020

Cross-Origin Resource Sharing in WEB API

 Admin     April 23, 2020     .Net, Web API     No comments   

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

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 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape