Pete rudensky
Pete rudensky

Reputation: 484

How to enable cors in ASP.NET Core 6.0 Web API project?

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();

Upvotes: 35

Views: 100709

Answers (7)

Gilbert
Gilbert

Reputation: 3334

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

Upvotes: 11

Aya Osama
Aya Osama

Reputation: 131

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);
      

Upvotes: 0

Daniel
Daniel

Reputation: 834

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();

Upvotes: 58

Jawad Fadel
Jawad Fadel

Reputation: 828

Works with me

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

Upvotes: 3

Fritz
Fritz

Reputation: 943

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

Upvotes: 2

gerb0n
gerb0n

Reputation: 440

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.

Upvotes: 5

MaartenDev
MaartenDev

Reputation: 5811

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

Upvotes: 0

Related Questions