Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
F

FluentHttpClient

> 开发工具
Open source

A modern async HTTP client for REST APIs. Its fluent interface lets you send an HTTP request and parse the response in one go.

357 stars0 likes2 views
WebsiteGitHub

About

A modern async HTTP client for REST APIs. Its fluent interface lets you send an HTTP request and parse the response in one go.

FluentHttpClient is a modern async HTTP client for REST APIs. Its fluent interface lets you send an HTTP request and parse the response in one go — hiding away the gritty details like deserialisation, content negotiation, optional retry logic, and URL encoding:

csharp
Blog result = await new FluentClient("https://example.org/api")
   .GetAsync("blogs")
   .WithArgument("id", 15)
   .WithBearerAuthentication(token)
   .As();

Designed with discoverability and extensibility as core principles, just autocomplete to see which methods are available at each step.

Contents

  • Why does this exist?
  • Get started
    • Install
    • Basic usage
    • URL arguments
    • Body
    • Headers
    • Read the response
    • Read the response info
    • Handle errors
  • Advanced features
    • Request options
    • Simple retry policy
    • Cancellation tokens
    • Custom requests
    • Synchronous use
  • Extensibility
    • Custom formats
    • Custom filters
    • Custom retry/coordination policy
    • Custom HTTP
    • Mocks for unit testing

Why does this exist?

.NET has a built-in HttpClient, and there are various higher-level HTTP clients. However:

  • Using HttpClient can be tedious, with lots of repeated boilerplate code and low discoverability. Usage also varies depending on your .NET version (and it isn't available at all in some older versions), which makes multi-targeting harder.
  • Higher-level client libraries often reinvent the wheel. That means you can lose access to the features, performance optimizations, best practices & patterns, and ecosystem of libraries which come with using the built-in HttpClient.

FluentHttpClient offers a middle ground: it's a thin wrapper around the .NET HttpClient which greatly simplifies its API and makes it consistent across .NET versions, but you're still using the official HttpClient with all the benefits that provides.

For example, this code using FluentHttpClient:

csharp
using var client = using new FluentClient("https://example.org/api");
Blog result = await client
   .GetAsync("blogs")
   .WithArgument("search", searchText)
   .WithBearerAuthentication(token)
   .As();

Is equivalent to this code when using HttpClient directly:

…

And that's just a simple example; the HttpClient code can become much more complex if you want any of the other features built-in to FluentHttpClient like content negotiation, retry logic, error-handling, filters, etc.

Get started

Install

Install it [from NuGet][Pathoschild.Http.FluentClient]:

Install-Package Pathoschild.Http.FluentClient

The client works on most platforms (including Linux, Mac, and Windows):

platform min version
.NET 5.0
.NET Core 1.0
.NET Framework 4.5.2
[.NET Standard][] 1.3
Mono 4.6
Unity 2018.1
Universal Windows Platform 10.0
Xamarin.Android 7.0
Xamarin.iOS 10.0
Xamarin.Mac 3.0

Basic usage

Just create the client and chain methods to set up the request/response. For example, this sends a GET request and deserializes the response into a custom Item class based on content negotiation:

csharp
Item item = await new FluentClient()
   .GetAsync("https://example.org/api/items/14")
   .As();

You can also reuse the client for many requests (which improves performance using the built-in connection pool), and set a base URL in the constructor:

csharp
using var client = new FluentClient("https://example.org/api");

Item item = await client
   .GetAsync("items/14")
   .As();

The client provides methods for DELETE, GET, POST, PUT, and PATCH out of the box. You can also use SendAsync to craft a custom HTTP request.

URL arguments

You can add any number of arguments to the request URL with an anonymous object:

csharp
await client
   .PostAsync("items/14")
   .WithArguments(new { page = 1, search = "some search text" });

Or with a dictionary:

csharp
await client
   .PostAsync("items/14")
   .WithArguments(new Dictionary { … });

Or individually:

csharp
await client
   .PostAsync("items/14")
   .WithArgument("page", 1)
   .WithArgument("search", "some search text");

Body

You can add a model body directly in a POST or PUT:

csharp
await client.PostAsync("search", new SearchOptions(…));

Or add it to any request:

csharp
await client
   .GetAsync("search")
   .WithBody(new SearchOptions(…));

Or provide it in various formats:

format example
serialized model WithBody(new ExampleModel())
form URL encoded WithBody(p => p.FormUrlEncoded(values))
file upload WithBody(p => p.FileUpload(files))
HttpContent WithBody(httpContent)

Headers

You can add any number of headers:

csharp
await client
   .PostAsync("items/14")
   .WithHeader("User-Agent", "Some Bot/1.0.0")
   .WithHeader("Content-Type", "application/json");

Or use methods for common headers like WithAuthentication, WithBasicAuthentication, WithBearerAuthentication, and SetUserAgent.

(Basic headers like Content-Type and User-Agent will be added automatically if you omit them.)

Read the response

You can parse the response by awaiting an As* method:

csharp
await client
   .GetAsync("items")
   .AsArray();

Here are the available formats:

type method
Item As()
Item[] AsArray()
byte[] AsByteArray()
string AsString()
Stream AsStream()
JToken AsRawJson()
JObject AsRawJsonObject()
JArray AsRawJsonArray()

The AsRawJson method can also return dynamic to avoid needing a model class:

csharp
dynamic item = await client
   .GetAsync("items/14")
   .AsRawJsonObject();

string author = item.Author.Name;

If you don't need the content, you can just await the request:

csharp
await client.PostAsync("items", new Item(…));

Read the response info

You can also read the HTTP response info before parsing the body:

csharp
IResponse response = await client.GetAsync("items");
if (response.IsSuccessStatusCode || response.Status == HttpStatusCode.Found)
   return response.AsArray();

Handle errors

By default the client will throw ApiException if the server returns an error code:

csharp
try
{
   await client.Get("items");
}
catch(ApiException ex)
{
   string responseText = await ex.Response.AsString();
   throw new Exception($"The API responded with HTTP {ex.Response.Status}: {responseText}");
}

If you don't want that, you can...

  • disable it for one request:

    csharp
    IResponse response = await client
       .GetAsync("items")
       .WithOptions(ignoreHttpErrors: true);
  • disable it for all requests:

    csharp
    client.SetOptions(ignoreHttpErrors: true);
  • use your own error filter.

Advanced features

Request options

You can customize the request/response flow using a few built-in options.

You can set an option for one request:

csharp
IResponse response = await client
   .GetAsync("items")
   .WithOptions(ignoreHttpErrors: true);

Or for all requests:

csharp
client.SetOptions(ignoreHttpErrors: true);

The available options are:

option default effect
ignoreHttpErrors false Whether HTTP error responses like HTTP 404 should be ignored (true) or raised as exceptions (false).
ignoreNullArguments true Whether null arguments in the request body and URL query string should be ignored (true) or sent as-is (false).
completeWhen ResponseContentRead When we should stop waiting for the response. For example, setting this to ResponseHeadersRead will let you handle the response as soon as the headers are received, before the full response body has been fetched. This only affects getting the IResponse; reading the response body (e.g. using a method like IResponse.As()) will still wait for the request body to be fetched as usual.

Simple retry policy

The client won't retry failed requests by default, but that's easy to configure:

csharp
client
   .SetRequestCoordinator(
      maxRetries: 3,
      shouldRetry: request => request.StatusCode != HttpStatusCode.OK,
      getDelay: (attempt, response) => TimeSpan.FromSeconds(attempt * 5) // wait 5, 10, and 15 seconds
   );

Chained retry policies

You can also wrap retry logic into IRetryConfig implementations:

…

Then you can add one or more retry policies, and they'll each be given the opportunity to retry a request:

csharp
client
   .SetRequestCoordinator(new[]
   {
      new TokenExpiredRetryConfig(),
      new DatabaseTimeoutRetryConfig(),
      new RetryWithBackoffConfig()
   });

Note that there's one retry count across all retry policies. For example, if TokenExpiredRetryConfig retries once before falling back to RetryWithBackoffConfig, the latter will receive 2 as its first retry count. If you need more granular control, see custom retry/coordination policy.

Cancellation tokens

The client fully supports [.NET cancellation tokens][] if you need to cancel requests:

csharp
using var tokenSource = new CancellationTokenSource();

await client
   .PostAsync(…)
   .WithCancellationToken(tokenSource.Token);

tokenSource.Cancel();

The cancellation token is used for the whole process, from sending the request to reading the response. You can change the cancellation token on the response if needed, by awaiting the request and calling WithCancellationToken on the response.

Custom requests

You can make changes directly to the HTTP request before it's sent:

csharp
client
   .GetAsync("items")
   .WithCustom(request =>
   {
      request.Method = HttpMethod.Post;
      request.Headers.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromMinutes(30) };
   });

Synchronous use

The client is built around the async and await keywords, but you can use the client synchronously. That's not recommended — it complicates error-handling (e.g. errors get wrapped into [AggregateException][]), and it's very easy to cause thread deadlocks when you do this (see [Parallel Programming with .NET: Await, and UI, and deadlocks! Oh my!][] and [Don't Block on Async Code][]).

If you really need to use it synchronously, you can just call the Result property:

csharp
Item item = client.GetAsync("items/14").Result;

Or if you don't need the response:

csharp
client.PostAsync("items", new Item(…)).AsResponse().Wait();

Extensibility

Custom formats

The client supports JSON and XML out of the box. If you need more, you can...

  • Add any of the existing [media type formatters][]:

    csharp
    client.Formatters.Add(new YamlFormatter());
  • Create your own by subclassing MediaTypeFormatter (optionally using the included MediaTypeFormatterBase class).

Custom filters

You can read and change the underlying HTTP requests and responses by creating IHttpFilter implementations. They can be useful for automating custom authentication or error-handling.

For example, the default error-handling is just a filter:

csharp
/// Method invoked just after the HT

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#httphttp-clientrest

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具