【问题标题】:.NET API returns 404 response to preflight requests.NET API 对预检请求返回 404 响应
【发布时间】:2022-01-25 09:48:10
【问题描述】:

我想将 .NET Web API 上传到域,然后设置前端以连接到它。问题是由于同源策略,我无法向 API 域发送请求。我尝试使用 CORS 并允许所有来源,但由于凭据是通过响应发送的,我必须指定可以连接到 API 的确切域。

这是我在后端项目中使用的代码:

app.UseCors(x => x 
            .WithOrigins("https://localhost:3000")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

当我尝试登录时,我在控制台中收到此错误:

Access to fetch at 'https://api.paykanpars.com/api/user/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

当我在 localhost 上运行 API 时,这可以正常工作,但是当我在生产主机上运行它时,它会返回 404 状态以响应预检请求。生产主机使用 Plesk 作为其网络主机。

【问题讨论】:

  • 你能在你的 ConfigureServices 中试试这个吗: services.AddCors(options => options.AddDefaultPolicy(policy => policy.AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetIsOriginAllowed(_ => true )));这在您的配置中:app.UseCors();如果它有效,您可以修改它以阻止来自 3000 以外的请求
  • 那也不行。

标签: http asp.net-web-api cors plesk


【解决方案1】:

尝试使用这种语法

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
                      builder =>
                       {
                       builder.AllowAnyOrigin()
                              .AllowAnyMethod()
                              .AllowAnyHeader();
              }));

        .....
            
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            .....

           // app.UseRouting();

            app.UseCors("AllowAnyOrigin");

         //  app.UseAuthorization();
         // app.UseEndpoints(..
 
         }

确保 UseCors 应该在 Configure 方法的末尾,但在 UseAuthorizaton 之前。 AddCors 应该位于配置服务的顶部。

如果它有效,那么你可以替换

  builder.AllowAnyOrigin()

  builder.WithOrigins("https://localhost:3000")

【讨论】:

  • 感谢您的回复,但我需要.AllowCredentials() 来发送用户凭据并设置刷新令牌cookie,而.AllowCredentials() 不能与builder.AllowAnyOrigin() 一起使用。我已经尝试过.SetIsOriginAllowed(_ => true),当我在本地主机而不是服务器上运行它时效果很好。服务器始终以错误代码 404 响应预检请求。
猜你喜欢
  • 2021-04-29
  • 1970-01-01
  • 2018-08-19
  • 2018-05-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
相关资源
最近更新 更多