首页 > 解决方案 > 如何在 F# Saturn Framework 中获取查询参数?

问题描述

假设我们有这个 Web 服务器来处理请求:

let webApp = scope {
    get  "/api/zoo/animals/"    (getAllAnimals())
    getf "/api/zoo/animals/%s"  getAnimalInfo
}

此语法在文档中进行了描述,并在示例中进行了演示。

现在,如果我想在 url 查询中有一个参数,例如过滤结果怎么办?

http://localhost:8080/api/zoo/animals?type=mammals

这不会做任何事情:

getf "/api/zoo/animals?type=%s" getAnimalsByType

标签: f#f#-giraffesaturn-framework

解决方案


请参阅此处的示例:

https://github.com/giraffe-fsharp/Giraffe/blob/master/DOCUMENTATION.md#query-strings

它显示了如何绑定来自查询字符串的数据,因此您不必使用 GetQueryStringValue

在你的情况下,我认为这样的事情可能会奏效。

[<CLIMutable>]
type AnimalType =
    { type : string }

let animal (next : HttpFunc) (ctx : HttpContext) =
    // Binds the query string to a Car object
    let animal = ctx.BindQueryString<AnimalType>()

    // Sends the object back to the client
    Successful.OK animal next ctx

let web_app  =

    router {    
        pipe_through (pipeline { set_header "x-pipeline-type" "Api" })
        post "/api/animal" animal
    }

推荐阅读