如何在长颈鹿中启用CORS?

时间:2017-10-12 19:57:10

标签: asp.net-web-api f# asp.net-core-webapi f#-giraffe

我无法使用发送请求的Elm客户端在服务器上使用Giraffe框架成功执行Post操作。

尝试测试http请求时收到以下消息:

  

info:Microsoft.AspNetCore.Hosting.Internal.WebHost 1

  Request starting HTTP/1.1 OPTIONS http://localhost:5000/register  0 
     

Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求

     

启动HTTP / 1.1选项http://localhost:5000/register 0 dbug:   Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware 1

  OPTIONS requests are not supported

服务实施如下:

let private registrationHandler = 
    fun(context: HttpContext) -> 
        async {
            let! data = context.BindJson<RegistrationRequest>()
            match register data with
              | Success profile -> return! json profile context
              | Failure         -> return! (setStatusCode 400 >=> json "registration failed") context
        }

然后我尝试了以下内容并观察到相同的结果:

let private registrationHandler = 
    fun(context: HttpContext) -> 
        async {
            return! text "hello world" context
        }

附录

    POST >=> 
        choose [
            route "/register" >=> registrationHandler
        ]

可以找到源文件here

Elm and CORS

WebAPI enable Cors

这是一个显示支持Cors的代码的Giraffe sample

1 个答案:

答案 0 :(得分:2)

  1. 添加包:Microsoft.AspNetCore.Cors
  2. 在.fs文件中添加:

    打开Microsoft.AspNetCore.Cors

  3. 添加UseCors,例如:

    let configureApp (app : IApplicationBuilder) = app.UseGiraffeErrorHandler errorHandler app.UseStaticFiles() |> ignore app.UseAuthentication() |> ignore app.UseCors(new Action<_>(fun (b: Infrastructure.CorsPolicyBuilder) -> b.AllowAnyHeader() |> ignore; b.AllowAnyMethod() |> ignore)) |> ignore app.UseGiraffe webApp

  4. 在服务中添加cors:

    let configureServices (services : IServiceCollection) = let sp = services.BuildServiceProvider() let env = sp.GetService() let viewsFolderPath = Path.Combine(env.ContentRootPath, "Views")

    services
        .AddCors()
        .AddAuthentication(authScheme)
        .AddCookie(cookieAuth)
    |> ignore
    

    services .AddCors() .AddAuthentication(authScheme) .AddCookie(cookieAuth) |> ignore