CORS 对 dotnet 核心 3.1 预检响应的问题 [英] Problems with CORS Response to preflight in dotnet core 3.1
问题描述
我正面临这个问题:
在 'http://localhost:5000/api/surpactemp/' 处访问 XMLHttpRequest来自 origin '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 上传递 headers 对象,然后,我收到错误:
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 核心 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/en-us/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();
这篇关于CORS 对 dotnet 核心 3.1 预检响应的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!