While CORS is a big issue when working ReactJS in combination with ASP.Net-Core I figured out how to enable CORS so when accessing my UI (http://localhost:3000
) which uses SignalR/REST-Calls against the API (http://localhost:51761
).
Here the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(option =>
{
option.AddPolicy("myCors",
builder =>
{
builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin =>
{
if (origin.StartsWith("http://localhost")) return true;
if (origin.StartsWith("http://vdedarh02331")) return true;
if (origin.StartsWith("http://10.65.1.23")) return true;
return false;
});
});
});
services.AddControllers();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SimpleAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("myCors");
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
On my React Application I am doing the following API call:
axios
.post("http://localhost:51761/Simple/Login")
.then((response) => console.log(response))
.catch((error) => {
console.error(error);
console.log("Trying to use IP");
axios
.post("10.65.1.23:51761/Simple/Login")
.then((resp) => console.log(resp))
.catch((err) => console.error(err));
});
Opening the UI via Browser with URL http://10.65.1.23:3000
works fine. Doing a request against the API results into following error.
It makes sense that calling localhost:51761
wouldnt work because the browser is trying to call the API on the browsers machine.
When debugging the server code on the inner function of SetIsOriginAllowed
I recognized that the origin will always be evaluated everytime I do a request when using the UI on my dev-machine (localhost
) but never when using a different machine.
Did I missunderstood CORS or did a wrong setup? Thanks for your help!