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

wba*_*ail 3 c# .net-core asp.net-core asp.net-core-webapi angular

我面临这个问题:

从源“ http://localhost: 4200”访问位于“ http://localhost: 5000/api/surpactemp/”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:重定向是不允许用于预检请求。

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

.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
Run Code Online (Sandbox Code Playgroud)

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

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

环境

  • 点网核心 3.1
  • 角8

后端: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();
 });

Run Code Online (Sandbox Code Playgroud)

前端: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);

Run Code Online (Sandbox Code Playgroud)

参考:https://learn.microsoft.com/en-us/aspnet/core/security/cors ?view=aspnetcore-3.1#preflight-requests

wba*_*ail 16

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

在方法Startup.csConfigure

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

app.UseRouting();

app.UseCors();

app.UseAuthorization();

Run Code Online (Sandbox Code Playgroud)