我正在编写以下代码以发布到Web API。但是,我在client.PostAsJsonAsync
的行上遇到了编译器错误。错误消息是
Error This expression was expected to have type
Async<'a>
but here has type
Tasks.Task<HttpResponseMessage>
代码:
[<CLIMutable>]
type Model = { ..... }
let PostIt params = async {
use client = new HttpClient()
let content = { ..... } // a Model built from params
let! response = client.PostAsJsonAsync("http://...", content) // Error!
return response }
在F#中处理Restful API的最佳方法是什么?我正在使用Fsharp.Data。
答案 0 :(得分:5)
您似乎需要使用Async.AwaitTask
:
let! response = Async.AwaitTask (client.PostAsJsonAsync("http://...", content))
或使用|>
运算符:
let! response = client.PostAsJsonAsync("http://...", content) |> Async.AwaitTask
答案 1 :(得分:4)
如果您已有F#Data引用,也可以使用F# Data HTTP utilities执行此操作,{{3}}提供了一个用于发出HTTP请求的F#友好API。
async {
let! response =
Http.AsyncRequest
( "http://httpbin.org/post", httpMethod = "POST",
headers = [ ContentType HttpContentTypes.Json ],
body = TextRequest """ {"test": 42} """)
return response }
F#Data不会自动为您自动序列化数据,因此使用这些实用程序的缺点是您需要在发出请求之前明确地序列化数据。