Search code examples
c#.netcorsasp.net-core-webapi

How Can I Resolve the No 'Access-Control-Allow-Origin' CORS Error on my Webpage?


I've created a web page that fetches data from my .NET Core Web API I've built in C# using the .NET Framework 8.0. My webpage and api are hosted on the same server, just on different ports. When I try to call the api, the console spits out the following error:

Access to fetch at 'api address' from origin 'webpage address' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

One of the first steps I took to rectify my problem was lookup the documentation Microsoft has for Enabling Cross-Origin Requests in ASP.NET Core. I scrolled to the section CORS with default policy and middleware and changed the code in Program.cs as follows:

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

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("Webpage Address", "API Address")
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

var app = builder.Build();

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

app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();

I was still getting the CORS error with this code, so I tried the following changes, which still resulted in the error:

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.AllowAnyOrigins()
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

I also tried configuring my code according to the CORS with named policy and middleware section, but with the same results outlined above. Can anyone assist?


Solution

  • The problem I was experiencing was due to the fact that the server I was using to host my API didn't have the .NET Hosting Bundle installed.

    Once it was installed, I configured my CORS policy to allow one specific origin, and everything worked as intended.