dotnet core 3.1中对预检的CORS响应问题 [英] Problems with CORS Response to preflight in dotnet core 3.1
问题描述
我正面临这个问题:
以" http://localhost:5000/api/surpactemp/"访问XMLHttpRequest来自来源" http://localhost:4200 "已被CORS策略阻止:对预检请求的响应未通过访问控制检查:飞行前请求不允许重定向.
Access to XMLHttpRequest at 'http://localhost:5000/api/surpactemp/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
在后端,我尝试过这种方法,但没有成功:
On backend side I tried this way and didn't worked:
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
我一直在尝试使用Microsoft参考(以下)解决问题的方法,但是到目前为止没有成功.另外,我已经尝试过不在Angular上传递标头对象,然后,我收到错误消息:
I've been trying several ways to solve using Microsoft reference (below), but, no success so far. Also, I already tried not pass the headers object on Angular, then, I receive the error:
请求中没有'Access-Control-Allow-Origin'标头
No 'Access-Control-Allow-Origin' header is present on the requested
环境:
- Dotnet Core 3.1
- 角度8
后端:Startup.cs
Backend: Startup.cs
//ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.WithHeaders(HeaderNames.ContentType, "application/json")
.WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")
);
});
//Configure
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
前端:form-service.ts
Frontend: form-service.ts
httpOptions = {
headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'withCredentials': 'false',
// 'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
};
return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);
参考: https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view = aspnetcore-3.1#preflight-requests
推荐答案
我发现了这个问题, app.UseHttpsRedirection()
方法需要 https
客户端.
I discovered the issue, the app.UseHttpsRedirection()
method requires https
clients.
在 Startup.cs
上的 Configure
方法:
//app.UseHttpsRedirection(); <-- Commented this line
app.UseRouting();
app.UseCors();
app.UseAuthorization();
这篇关于dotnet core 3.1中对预检的CORS响应问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!