Bansdns
Bansdns

Reputation: 25

ASP.NET Core - CORS error when posting the request despite allowing all origins

Whenever I send a POST request to my server from a frontend webpage I've made, the DevTools console throws the error below:

Access to fetch at 'http://127.0.0.1:5000/CreateBooking' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is my Program.cs:

using Microsoft.AspNetCore.HttpOverrides;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllers().AddNewtonsoftJson();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("http://127.0.0.1:5500")
            .AllowAnyHeader().AllowAnyMethod();
        }
        );
});
builder.WebHost.UseUrls("http://*:5000");
var app = builder.Build();

app.UseCors();

app.UseStaticFiles();


app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});

app.UseAuthorization();

app.MapControllers();

app.Run();

To post the request, I'm just using fetch with the header: "Content-Type": "application/json".

I've tried using a wildcard origin:

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("*")
            .AllowAnyHeader().AllowAnyMethod();
        }
        );
});

However, I still get the same error. I'm wondering if my builder isn't applying the policy or if something is inherently wrong with the way that I set the policy. Any help would be appreciated since this is my first fully-fledged app.

Upvotes: 2

Views: 79

Answers (1)

Yong Shun
Yong Shun

Reputation: 51420

From the CORS with named policy and middleware,

With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints.

Also based on the app.UseForwardedHeaders(), your middleware pipeline (structure) should be as:

var app = builder.Build();

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});


app.UseStaticFiles();

app.UseRouting();

app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();

Upvotes: 2

Related Questions