问题
I have a test app, which I want to send a request and get a token, but anyway I can't get it due to the cross request error in my back end in the configuration I have:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials().WithOrigins("http://localhost:4200");
}));
and added the following on the Configure part:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseCors("MyPolicy");
app.UseMvc();
}
but still getting the error saying has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
回答1:
Put services.AddCors
in the top of your ConfigureSevices
method, then configure cors that way:
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:4200", "https://localhost:4200");
}));
In Configure
method add app.UseCors("MyPolicy");
at the top of method too. That works fine for me, but before i tried a lot of variants which did not.
来源:https://stackoverflow.com/questions/61443057/cors-request-error-even-thought-its-enabled-in-the-net-core-back-end