CORS Policy in ASP.NET CORE APPLICATION

 Overview 

Hello all techy world members...

Today we are working with APIs (Application Programming Interface). So keep some questions in your mind:

  1. How do APIs work?
  2. Are they secure?
  3. What are the ways to secure APIs?
  4. How to apply restrictions with domain names, particular APIs, and API types (GET, POST, PUT, DELETE)?

Now we will talk about a trending keyword related to APIs: CORS policy.

CORS stands for Cross-Origin Resource Sharing. As per the name, it defines how we can share APIs with domains, types, etc.

In this article, we will discuss the most trending term in the API world called CORS Policy. This is particularly relevant for popular frontend frameworks like Angular, React.js, Vue.js, Next.js, etc., and how to manage the security of these APIs.

  • What is CORS policy?
  • Why is it necessary for APIs?
  • How to implement CORS policy?
  • Where can we implement it?
    • Action Method level
    • Controller level
    • Globally
  • How to disable the CORS policy?

CORS: CORS stands for Cross-Origin Resource Sharing, which means how two or more applications share resources. In the current scenario, we have web applications working alongside Android and iOS applications. Learn more in my other article.

Follow these steps to apply the CORS policy in your web API application:

  1. Open your Web API solution in Visual Studio.
  2. If you're working with an older version, open the Startup.cs file; for newer versions, open the Program.cs file.
  3. Register the CORS policy.
  4. In the Startup file, locate the ConfigureServices method.
  5. Code Below Avaiable 

Final Setup of Global Level


Now Working on Particular Action Method Level and Controller Level.


In the Controller level so we just same way declare the cors policy and use the policy in controller level with two approach.

  1. On full controller(Global level of controlletr)
  2. On Particular Action Method

Basic two thing is there just follow below of syntax for same thing working.

[EnableCors("Policy1")]

In this syntax we declare the policy1 is the policy name.
In the same way we declare the CORS policy on Action Method Level so we just put the before HTTP verbs.

Post a Comment

1 Comments

thanks for your suggestion and improving quality of the content