dotnet core 3.1 中 CORS 响应预检的问题

2024-01-11

我面临这个问题:

访问 XMLHttpRequest 位于 'http://localhost:5000/api/surpactemp/ http://localhost:5000/api/surpactemp/'从原点'http://本地主机:4200 http://localhost:4200' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

在后端,我尝试了这种方法,但没有成功:

.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()

我一直在尝试使用 Microsoft 参考(如下)的多种方法来解决问题,但是到目前为止还没有成功。 另外,我已经尝试不在 Angular 上传递 headers 对象,然后,我收到错误:

请求中不存在“Access-Control-Allow-Origin”标头

环境:

  • 点网核心 3.1
  • 角8

Backend:启动.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();
 });

Frontend: 表单服务.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://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests


我发现了这个问题,app.UseHttpsRedirection()方法要求https客户。

On Startup.cs at Configure method:

//app.UseHttpsRedirection(); <-- Commented this line

app.UseRouting();

app.UseCors();

app.UseAuthorization();

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

dotnet core 3.1 中 CORS 响应预检的问题 的相关文章

随机推荐