35

Configured CORS in my ASP.NET Core 6.0 Web API project. But the preflight request receives a http 405 error.

In other words HTTP OPTION is not allowed. Looks like cors is not enabled.

I've seen examples with config.EnableCors(); but there is no App_Start/WebApiConfig.cs in this project template.

What am I missing here?

Program.cs

var builder = WebApplication.CreateBuilder(args);

// 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 devCorsPolicy = "devCorsPolicy";
builder.Services.AddCors(options =>
{
    options.AddPolicy(devCorsPolicy, builder => {
        //builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
        //builder.SetIsOriginAllowed(origin => true);
    });
});


var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors(devCorsPolicy);
}
else 
{
    app.UseHttpsRedirection();
    app.UseAuthorization();
    //app.UseCors(prodCorsPolicy);
}

app.MapControllers();

app.Run();
10
  • BTW, app.UseCors(devCorsPolicy); line is being hit. Commented Dec 28, 2021 at 19:24
  • 1
    Are you sure this is on .NET Core 2.2 ?? The code looks more like the "simplified" templates included in .NET (Core) 6.0 .... Commented Dec 28, 2021 at 19:27
  • It's the web api version on .NET 6 Commented Dec 28, 2021 at 19:28
  • Where are you getting CORS errors? In the browser or in swagger? Commented Dec 28, 2021 at 19:31
  • 1
    Thanks @marc_s for the edits Commented Dec 28, 2021 at 19:37

7 Answers 7

58

Add service builder.Services.AddCors and app add app.UseCors("corsapp");

replace builder.WithOrigins("*") with builder.WithOrigins("http://localhost:800", "https://misite.com");

check documentation

     var builder = WebApplication.CreateBuilder(args);

    
    // 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();
    //services cors
    builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
    {
        builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
    }));
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        
    }
       //app cors
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseCors("corsapp");
        app.UseAuthorization();

        //app.UseCors(prodCorsPolicy);

    app.MapControllers();
    
    app.Run();
Sign up to request clarification or add additional context in comments.

3 Comments

It's important to note that the UseCors invocation must be placed between UseRouting and UseEndpoints invocations if they are present.
@Tacoタコス Of course, order is always important in services.
@Hazelへいぜる why plz?
11

This CORS thing can be a headache to set especially for the first time. But by being precise you can do.

In your Program.cs file, make the following change. Notice that there are two changes to be made one above and another below the var app = ... statement:

builder.Services.AddCors(policyBuilder =>
    policyBuilder.AddDefaultPolicy(policy =>
        policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod())
);

var app = builder.Build();
app.UseCors();

If you are specifying an actual origin, make sure you include the http part for example:

...
policy.WithOrigins("http://localhost:3000")

Your web browser code making the request should also be in point. Here is the request in javascript using axios:

import axios from "axios";

const api = 'http://localhost:5000'

/**
 * 
 * @returns {TransferHeader[]}
 */
export const fetchTransfers = async () => {
    const { data } = await axios({
        method: 'get',
        url: `${api}/api/transfers`,
        // withCredentials: true
    })
    console.log(data)
    return data 
}


Setting cors is only required when the api is being called by the web browser. If the calls are coming from the server like it is for nextjs' server components, setting up cors may not be required

Comments

5

For anyone making the same mistake as me: Make sure your client application calling the Web API has the correct url with https:// scheme. So localhost:8100/api should be https://localhost:8100/api.

1 Comment

ooooooooooh bro. That was my problem also. I was struggling with CORS, but it was all about the correct url. Thx a lot
3

Works with me

app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials());

Comments

2

I had the issue that I believed the wildcard option works out of the box for ports too. When I set the correct port it worked. (http://localhost:* does NOT work!)

        services.AddCors(options =>
        {
            options.AddPolicy(AllowCorsPolicyName,
                builder =>
                {
                    builder
                        .WithOrigins(
                            "http://localhost:5173",
                            "http://localhost:5174",
                            "https://*.example.com",
                            )
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
        });
        // With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints.
        app.UseCors(AllowCorsPolicyName);

Docs can be found here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0

When using app.UseHttpsRedirection() and you call the http endpoint it will also not work

Comments

0

The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.

fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))

Results in the following response:
enter image description here

Comments

0

Reference to Microsoft Documentation

You've to follow some steps to enable CORS (Cross-Origin Resource Sharing)

  1. In Program class :
    • Set a policy name "It's optional but 'll help you to avoid repeat write it multi times".

      var  MyAllowedOrigins = "_myCORS";
      
    • Configure CORS service.

      builder.Services.AddCors(options =>{
           options.AddPolicy(name: MyAllowedOrigins ,
                   policy  =>
                   {
                       policy.WithOrigins("Write URL here")
                       .AllowAnyHeader()
                       .AllowAnyMethod()
                       .AllowCredentials());
                   });
            }); 
      
    • Add CORS Middleware to handle cross-origin requests before authorization.

      app.UseCors(MyAllowedOrigins);
      

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.