Efficiently Handle HTTP Requests with Flurl in .NET

Efficiently Handle HTTP Requests with Flurl in .NET

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

Last updated 6/24/2022 9:45 PM
SpringLeee
3 min read
Category
.NET
Tags
.NET C# Flurl

Introduction

According to the official documentation, Flurl is a modern, fluent, asynchronous, testable, portable URL builder and HTTP client component.

URL Building

Suppose there is a login endpoint with the following address:

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

When handling this URL, we typically concatenate "login", then a "?" symbol, and then the parameters, separating them with "&" to get the final address.

With Flurl, you first need to install the Flurl component via NuGet.

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

That's simple — this is the most basic GET request. We can also use extension methods on Uri.

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

HTTP Enhancements

Flurl is modular, so you also need to install Flurl.Http.

using Flurl;
using Flurl.Http;

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

The code above sends a GET request and returns an IFlurlResponse, which provides access to StatusCode, Headers, etc. You can also get the response content via GetStringAsync and GetJsonAsync.

If you just want to retrieve the response content, 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 Submission

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

Dynamic Types

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

Setting Request Headers:

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 avoid creating too many HttpClient instances, as excessive connections can exhaust server resources and often throw SocketException. Most people prefer using HttpClientFactory.

In the Flurl library, it manages HttpClient instances internally. Typically, one HttpClient is created per host and cached for reuse.

Flurl also supports IoC containers well, so you can use it with dependency injection.

Summary

The Flurl component makes HTTP operations simpler and more user-friendly. Give it a try in your projects. There are other features like testability and configurability – you can find the documentation on its official website.

Welcome to scan the QR code to follow our official account 【半栈程序员】, focusing on translations of excellent foreign blogs and sharing open source projects.

Keep Exploring

Related Reading

More Articles