Enable Cross Origin Requests (CORS) in ASP.NET Core API

Enable cross origin access to ASP.NET Core Web API Application

September 15, 2020

In this article we will cover how to Enable cross origin access to the ASP.NET Core Web API.

CORS can be enabled for specific and all Origin. It can be enabled at the controller and action level. It Can also be enabled on method type (GET, POST, ETC).

Enable for all origin

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CORSPolicy"corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    );
            });
        }

Enable for specific origin

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CORSPolicy"corsPolicyBuilder => corsPolicyBuilder
                    .WithOrigins("https://localhost:44323""http://anydomain.com")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    );
            });
        }

Enable with specific Methods

public void ConfigureServices(IServiceCollection services)
       {
           services.AddCors(options =>
           {
               options.AddPolicy("CORSPolicy"corsPolicyBuilder => corsPolicyBuilder
                  .WithOrigins("https://localhost:44323""http://anydomain.com")
                  .WithMethods("PUT""DELETE")
                  .AllowAnyHeader()
                  );
           });
       }

If you are enabling CORS for Specific types of Method (GET, POST, ETC) then you have to define [DisableCors] for all other types of Methods.

Configure method

public void Configure(IApplicationBuilder appIWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
 
            app.UseRouting();
 
            app.UseCors("CORSPolicy"); // CORS WILL BE ENABLED FOR ALL THE CONTROLLERS AND METHODS
 
            app.UseCors(); // WE WILL NEED TO APPLY 'CORSPolicy' AT CONTROLLERS AND METHODS LEVEL
 
            app.UseMiddleware<ExceptionMiddleware>();
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Enable CORS at Controller and Action Level

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using HpBlogs.Models;
using System.Collections.Generic;
 
namespace HpBlogs.Controllers
{
    [EnableCors("CORSPolicy")]  // WILLL ENABLE CORS FOR ENTIRE CONTROLLER
    [Route("api/[controller]")]
    public class CityController : Controller
    {
        [EnableCors("CORSPolicy")] // WILLL ENABLE CORS FOR SPECIFIC (States()) Method
        [Route("[States]")]
        [HttpGet]
        public IEnumerable<StateStates()
        {
            return null;
        }
        [EnableCors("CORSPolicy")]
        [Route("[Cities]")]
        [HttpGet]
        public IEnumerable<CityCities()
        {
            return null;
        }
        [DisableCors// WILLL DISABLE CORS FOR SPECIFIC (Locations()) Method
        [Route("[Locations]")]
        [HttpGet]
        public IEnumerable<LocationLocations()
        {
            return null;
        }
    }
}

Note:

1) app.UseCors("CORSPolicy"); OR app.UseCors(); Should be placed

After

app.UseRouting();

and Before

a) app.UseMiddleware

b) app.UseAuthentication();

c) app.UseAuthorization();

d) app.UseEndpoints

2)If you are enabling CORS for Specific types of Method (GET, POST, ETC) then you have to define [DisableCors] for all other types of Methods.

Additional References:

1) https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...