CORS policy in Javascript and .NET Minimal API

Viewed 1683

I'm making a request with pure javascript for a Minimal API in .NET 6, but when I open it in the browser I get the following message:

Access to fetch at 'https://localhost:7252/v1/todos' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I've already added the CORS configuration in the API but it didn't work:

  • Endpoint call by JavaScript:
fetch('https://localhost:7252/v1/todos')
    .then(response => response.json()) ...
  • .NET API Program configuration

builder.Services.AddCors(options => options.AddDefaultPolicy(builder => 
{ 
    builder.WithOrigins(
        "https://localhost:7252/v1/todos",
        "https://localhost:7252");
}));

app.UseCors();

1 Answers

You may want to extend it a little

 app.UseCors(builder => builder
 .AllowAnyOrigin()
 .AllowAnyMethod()
 .AllowAnyHeader()
 .AllowCredentials());

here a full code sample

public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://example.com",
                                                  "http://www.contoso.com");
                          });
    });

    // services.AddResponseCaching();
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseCors(MyAllowSpecificOrigins);

    // app.UseResponseCaching();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
}

Asp Cors Sample

Related