【问题标题】:Enable Cors .Net Core启用 Cors .Net Core
【发布时间】:2019-10-18 20:56:18
【问题描述】:

在使用 WebApi2 的 C# 中,我使用 WebApi2 定义了以下端点:

[EnableCors("*", "*", "Post", SupportsCredentials = true)]
[HttpPost]
[Route("myRouting")]
public HttpResponseMessage MyEndPoint()
{
    //...some code
}

它通过调用它来工作:

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.withCredentials = true;
request.send();

尝试将其升级到 F# .Net Core,但未成功:

let webApp =
    choose [
        route "/" >=> text "Description"
        POST >=> routef "myRouting" myEndPoint ]

let configureCors (builder : CorsPolicyBuilder) =
    builder.AllowAnyOrigin()
           .AllowAnyHeader()
           .WithMethods("POST")
           .AllowCredentials()
           |> ignore

let configureApp (app : IApplicationBuilder) =
    app.UseCors(configureCors)
       .UseGiraffe webApp

let configureServices (services : IServiceCollection) =
    services.AddCors()
            .AddGiraffe() |> ignore

收到错误当请求的凭据模式为“包含”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“”。*

我知道指定 AllowAnyOrigin 和 AllowCredentials 是不安全的配置,可能导​​致跨站点请求伪造。当应用同时配置了这两种方法时,CORS 服务会返回无效的 CORS 响应。

为什么它可以与WebApi2 一起工作,有没有办法让它在不指定任何来源的情况下工作?

【问题讨论】:

  • 如果您尝试 .AllowAnyMethod() 是否有效?您可能需要允许“OPTIONS”方法
  • 好吧,我在预检时没有得到 405。实际上根本没有预检。

标签: .net-core f# cors


【解决方案1】:

我认为在configureServices 函数中使用services.AddCors 方法时需要添加策略。这是一个等效示例,使用您的配置改编自我在生产中使用的工作 F# .NET Core Web API:

let configureServices (services : IServiceCollection) =
    services.AddCors(fun options -> 
            options.AddPolicy("AllowAll", fun builder -> 
                 builder.AllowAnyHeader()
                        .AllowAnyOrigin()
                        .WithMethods("POST")
                        .AllowCredentials() |> ignore))
            .AddGiraffe()
            |> ignore

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2019-01-24
    • 2019-10-03
    • 2018-12-23
    • 2017-11-12
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多