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

问题描述 投票:-1回答:2

我正面临这个问题:

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

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

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

我一直在尝试几种方法来使用Microsoft参考进行解决(如下),但到目前为止没有成功。另外,我已经尝试过不在Angular上传递标题对象,然后,我收到错误消息:

请求中没有'Access-Control-Allow-Origin'标头

环境

  • Dotnet Core 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();
 });

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

c# angular asp.net-core .net-core asp.net-core-webapi
2个回答
0
投票

您可以使用代理配置。

看这个https://www.youtube.com/watch?v=D9oFe6rHjpY


0
投票
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc();       

 app.UseCors(
     options => options.WithOrigins("http://localhost:4200","https://localhost:4200")
                .AllowAnyHeader().AllowAnyMethod().AllowCredentials()
             );

编辑:

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(
         options => options.WithOrigins("http://localhost:4200", "https://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());




            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }     
© www.soinside.com 2019 - 2024. All rights reserved.