如何从F#中使用HttpClient? [英] How to consume HttpClient from F#?

查看:110
本文介绍了如何从F#中使用HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是F#的新手,并从C#开发人员的角度坚持了对F#异步的理解。假设在C#中包含以下代码段:

I'm new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#:

var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();

如何在F#中编写相同的内容?

How to write the same in F#?

推荐答案

这里是一个应执行所需功能的函数(请注意,您必须将代码包装在异步计算表达式中才能使用let!语法) :

Here is a function that should do what you're looking for (note that you'll have to wrap the code in an asynchronous computation expression in order to use the let! syntax):

let getAsync (url:string) = 
    async {
        let httpClient = new System.Net.Http.HttpClient()
        let! response = httpClient.GetAsync(url) |> Async.AwaitTask
        response.EnsureSuccessStatusCode () |> ignore
        let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask
        return content
    }

这篇关于如何从F#中使用HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆