http客户端post c#中的异步

http client post async in c#

我看过这个 example 在 F# 中执行 post 请求,但我想知道如何使用异步 post 请求

type Authentication = 
    new() = {}
    member this.RequestToken() =
        use client = new HttpClient()
        client.PostAsync "http://example.com"

        printfn "requestToken"

编辑

根据评论中的要求提供可比较的 C# 代码。

var body = "some data";

using (var client = new HttpClient(new HttpClientHandler { UseProxy = false })) {

    var response = await client.PostAsync("https://example.com", new StringContent(body, Encoding.UTF8, "application/xml"));
    var content = await response.Content.ReadAsStringAsync();
}

对于 F# 异步代码,您需要使用 async 计算表达式和 Async.AwaitTask 将 C# 的 Task<_> 类型转换为 F# 的 Async<_> 类型。我建议您查看一些有关 F# 异步工作流的文档。

type Authentication = 
    new() = {}
    member this.RequestToken() =
        async {
            use client = new HttpClient()
            let! response = client.PostAsync "http://example.com" |> Async.AwaitTask
            let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask
            return content
        }