Access-Control-Allow-Origin is missing when using app.UseCors in .NET 6

40 Views Asked by At
namespace CorsTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddCors(options =>
            {
                options.AddPolicy(name: "MyAllowSpecificOrigins", policy =>                                  {
                    policy.AllowAnyOrigin();
                });
            });

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseCors("MyAllowSpecificOrigins");

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

Please consider above codes, it is exactly the same as the WebAPI2 startup template, plus the following snippets added

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "MyAllowSpecificOrigins", policy =>                                  {
        policy.AllowAnyOrigin();
    });
});
app.UseCors("MyAllowSpecificOrigins");

These snippet is directly copied from MSDN. However, it just doesn't work properly. When I tried to fire a request in Swagger, the Access-Control-Allow-Origin header is missing, while I expect something like Access-Control-Allow-Origin: * will be included in the response. Thanks in advance for any advice

enter image description here

1

There are 1 best solutions below

1
Negi Rox On

Probably you need to add header also in policy

 policy.AllowAnyOrigin().AllowAnyHeader();
 policy.AllowAnyOrigin().WithHeaders("Access-Allow-Origin", "*");

for more visit this