Enable CORS in ASP.NET CORE WEB API

.NET CORS | How to Enable CORS in ASP.NET CORE WEB API

What is CORS

CORS stands for Cross-Origin Resource Sharing. It is an HTTP protocol that allows web applications to access resources hosted on different domains. In this article, we will learn How to Enable CORS in ASP.NET Core Web API.

How to Enable CORS

Enabling CORS in ASP.NET Core Web API is quite easy, as the platform comes with built-in features to support that.

Enable CORS Policy with Specific Origin

You need to configure CORS in the Program.cs file, if you are using below .NET 6 then configure CORS in the startup.cs file.

Open the Program.cs file in your editor and modify it. Here is how to enable CORS in ASP.NET Core.

   Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                 });
            });

app.UseCors("CorsPolicy");

Above code example, we are using the WithOrigins method, which accepts a list of string URIs as parameters, and allows you to specify multiple origins for a single CORS Policy.

Enable CORS Policy with any Origin

With this CORS policy, we are grating access to all origins “AllowAnyOrigin”, allowing any request header “AllowAnyHeader”, and permitting any HTTP method “AllowAnyMethod”

 Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyOrigin().
                    AllowAnyHeader().
                    AllowAnyMethod(); 
                 });
            });

app.UseCors("CorsPolicy");

CORS Policy Options

Here are the CORS policy options you can use to configure your ASP.NET Core WEB API:

  1. AllowAnyOrigin: To accept requests from any domain
  2. WithOrigins: To allow requests only from specific domains.
  3. WithMethods: to specify which HTTP methods are allowed in the request.
  4. AllowAnyMethod: To allow any HTTP method (GET, POST, PUT, etc.) in the request.
  5. AllowAnyHeader: To accept any HTTP request header.
  6. WithHeaders: To specify which HTTP headers are allowed in the request.
  7. WithExposedHeaders: To specify which headers are safe to expose to the API of a CORS API specification.
  8. AllowCredentials: To allow requests with credentials.

Conclusion

In this article, we have shown you how to enable CORS(Cross-Origin Resource Sharing) in an ASP.NET Core Web API. CORS is essential for allowing web applications hosted in different domains to access your API securely.

See More Articles:

Difference between IEnumerable and IQueryable in C#

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments