Using Flurl to efficiently handle Http requests in. NET

Using Flurl to efficiently handle Http requests in. NET

Flurl is a modern, fluent, asynchronous, testable, portable, URL-enhanced and Http client component.

最后更新 6/24/2022 9:45 PM
SpringLeee
预计阅读 3 分钟
分类
.NET
标签
.NET C# Flurl

profile

Officially, Flurl is a modern, fluent, asynchronous, testable, portable, URL-enhanced and Http client component.

URL construction

There is now a login interface with the following address:

https://www.some-api.com/login?name=Lee&pwd=123456

我们在处理这个地址的时候,会拼接 login, 然后拼接?号, 然后拼接参数,中间还要拼接& 得到最终的地址。

使用 Flurl 构建,首先需要通过 NuGet 安装 Flurl 组件。

var url = "http://www.some-api.com"
          .AppendPathSegment("login")
          .SetQueryParams(new
          {
              name = "Lee",
              pwd = "123456"
          });

It's simple, it's the simplest Get request, and we can also use Uri's extended method

var url = new Uri("http://www.some-api.com").AppendPathSegment(...

Http enhancement

Flurl 是模块化的,所以还需要安装 Flurl.Http

using Flurl;
using Flurl.Http;

var result = await "http://www.some-api.com".AppendPathSegment("login").GetAsync();

上面的代码会发送一个 GET 请求,并返回一个IFlurlResponse,可以得到 StatusCode,Headers 等,也可以通过 GetStringAsync 和 GetJsonAsync 得到响应内容。

If you just want to get responsive content, let's see how simple Flurl is:

T poco = await "http://api.foo.com".GetJsonAsync<T>();
string text = await "http://site.com/readme.txt".GetStringAsync();
byte[] bytes = await "http://site.com/image.jpg".GetBytesAsync();
Stream stream = await "http://site.com/music.mp3".GetStreamAsync();

**Post Submit **

await "http://api.foo.com".PostJsonAsync(new { a = 1, b = 2 });

** Dynamic type dynamic**

dynamic d = await "http://api.foo.com".GetJsonAsync();

** Set request header: **

await url.WithHeader("Accept", "text/plain").GetJsonAsync();

await url.WithHeaders(new { Accept = "text/plain", User_Agent = "Flurl" }).GetJsonAsync();

** Basic Authentication **

await url.WithBasicAuth("username", "password").GetJsonAsync();

OAuth 2.0

await url.WithOAuthBearerToken("mytoken").GetJsonAsync();

** Form submission **

await "http://site.com/login".PostUrlEncodedAsync(new {
    user = "user",
    pass = "pass"
});

HttpClient Management

We usually don't create too many HttpClients, too many connections will exhaust server resources, and we usually throw SocketException exceptions. Most of them still use HttpClientFactory.

In the Flurl library, it manages HttpClient instances internally. Usually, a host host will create an HttpClient and then cache it for reuse.

Flurl also supports IOC containers well, and you can also use it in dependency injection.

summary

The Flurl component makes Http operations easier and easier to use. You can try to use it in your project. There are other functions, testable and configurable, etc. You can find its documentation on the official website.

Welcome to scan the code and pay attention to our public account [Half-Stack Programmer], focusing on the translation of excellent foreign blogs and the sharing of open source projects.

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读