I'm currently building a Blazor WebAssembly application, which is displaying data from my ASP.NET Core 6 API. Note, that the projects are seperated in two different solutions.
The problem is that my API rejects the requests, which were send by my WASM application. Apparently that has to do with the CORS configuration of my API.
Access to fetch at 'https://localhost:7030/api/v1/test' from origin 'https://localhost:44338' 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.
The CORS configuration for the API is based on this answer by Aae Que.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigin("https://localhost:7198")
.AllowAnyMethod()
.AllowAnyHeader()
);
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
The service class, which is responsible for sending the requests, looks like the following.
public class TestService : ITestService
{
private readonly HttpClient _httpClient;
public TestService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetTest()
{
return await _httpClient.GetFromJsonAsync<string>("test");
}
}
The above service is implemented in Program.cs
.
builder.Services.AddSingleton<TestService>();
builder.Services.AddHttpClient<ITestService, TestService(client =>
{
client.BaseAddress = new Uri("https://localhost:7030/api/v1/");
});
Does anybody has an idea how I could solve my issue?
I highly appreciate any kind of help, cheers! :)