An open API service indexing awesome lists of open source software.

https://github.com/nagilum/fluenthttpclient

FluentHttpClient is a wrapper class for the native HttpClient in C# which provides fluent-like functions
https://github.com/nagilum/fluenthttpclient

Last synced: 3 months ago
JSON representation

FluentHttpClient is a wrapper class for the native HttpClient in C# which provides fluent-like functions

Awesome Lists containing this project

README

        

# FluentHttpClient

FluentHttpClient is a wrapper class for the native HttpClient in C# which provides fluent-like functions.

## Examples

If you want to get the HTML from a site:

```csharp
var html = await FluentHttpClient.Create("https://microsoft.com")
.GetAsync();
```

If you want to get an image as a stream with some headers:

```csharp
var stream = await FluentHttpClient.Create("https://url.yo/some/image")
.AddHeader("accept", "image/jpeg")
.GetAsync();
```

If you want to post some data that times out after 10 seconds:

```csharp
var obj = new
{
name = "Some Dude",
age = 43,
alive = true
};

var res = await FluentHttpClient.Create("https://some.url/that/takes/post")
.AddContent(obj, "application/json")
.SetTimeout(TimeSpan.FromSeconds(10))
.PostAsync();
```

## Constructors

There are two variations of the `Create` function.

```csharp
///
/// Create a new instance of the fluent HTTP client.
///
/// URL to request.
/// Whether to create a new HttpClient, or reuse the last one.
/// Fluent HTTP client instance.
FluentHttpClient Create(string url, bool createNewHttpClient = false)
```

```csharp
///
/// Create a new instance of the fluent HTTP client.
///
/// Uri to request.
/// Whether to create a new HttpClient, or reuse the last one.
/// Fluent HTTP client instance.
FluentHttpClient Create(Uri uri, bool createNewHttpClient = false)
```

The `url`/`uri` params is where you provide the URL to contact.

The `createNewHttpClient` param is for when you absolutely need to create a new instance of `HttpClient` under the hood.

As per Microsofts documentation:

> HttpClient is intended to be instantiated once and reused throughout the life of an application. In .NET Core and .NET 5+, HttpClient pools connections inside the handler instance and reuses a connection across multiple requests. If you instantiate an HttpClient class for every request, the number of sockets available under heavy loads will be exhausted. This exhaustion will result in SocketException errors.

However, the `AddCookie`, `AddCookies`, `SetTimeout`, and `SetUserAgent` fluent functions set data directly on the `HttpClient`, so if you make one request with a cookie added, and another after, the second request will contain the same cookie. If you need this to differ, that's where the `createNewHttpClient` param comes in. To force a new `HttpClient` under the hood, simply use set it to `true`.

## Fluent Functions

### AddContent

```csharp
///
/// Add content (payload) to request.
///
/// Content to add.
/// Content media type.
/// Content encoding.
/// Fluent HTTP client instance.
public FluentHttpClient AddContent(
object content,
string? contentType = null,
Encoding? encoding = null)
```

### AddCookie

```csharp
///
/// Add a cookie to request.
///
/// Cookie to add.
/// Fluent HTTP client instance.
public FluentHttpClient AddCookie(Cookie cookie)
```

### AddCookies

```csharp
///
/// Add several cookies to request.
///
/// Cookies to add.
/// Fluent HTTP client instance.
public FluentHttpClient AddCookies(params Cookie[] cookies)
```

### AddHeader

```csharp
///
/// Add header to request.
///
/// Name.
/// Value, if any.
/// Fluent HTTP client instance.
public FluentHttpClient AddHeader(string name, object? value = null)
```

### AddHeaders

```csharp
///
/// Add headers to request.
///
/// Headers to add.
/// Fluent HTTP client instance.
public FluentHttpClient AddHeaders(Dictionary headers)
```

### SetJsonSerializerOptions

```csharp
///
/// Set JSON serialization and deserialization options.
///
/// Options to set.
/// Fluent HTTP client instance.
public FluentHttpClient SetJsonSerializerOptions(JsonSerializerOptions options)
```

### SetTimeout

```csharp
///
/// Set request timeout.
///
/// Timeout.
/// Fluent HTTP client instance.
public FluentHttpClient SetTimeout(TimeSpan timeout)
```

### SetTimeout

```csharp
///
/// Set request timeout.
///
/// Timeout.
/// Fluent HTTP client instance.
public FluentHttpClient SetTimeout(int milliseconds)
```

### SetUserAgent

```csharp
///
/// Set user-agent for request.
///
/// User-agent.
/// Fluent HTTP client instance.
public FluentHttpClient SetUserAgent(string userAgent)
```

## Request Function

The request function, or one of the shorthand functions below, must be at the end of the fluent chain. The shorthand functions just use this main request function behind the scenes.

```csharp
///
/// Perform request.
///
/// HTTP method.
/// Cancellation token.
/// Response message.
public async Task SendAsync(
HttpMethod httpMethod,
CancellationToken ctoken = default)
```

## Shorthand Functions

If you don't want to use the `SendAsync` request function, you can use one of 5 shorthand functions that specify the HTTP method on their own. The only thing they do is use the `SendAsync` function behind the scenes with the HTTP method set.

They are:
* `DeleteAsync`
* `GetAsync`
* `PatchAsync`
* `PostAsync`
* `PutAsync`

## Different Return Types

By default `HttpClient` supports 4 different reads as well as the underlying `HttpResponseMessage` itself, so all these are implemented in the `FluentHttpClient` wrapper as well.

* `SendAsync()` will give you the raw `HttpResponseMessage`.
* `SendAsync()` will give you a byte-array of the response body.
* `SendAsync()` will give you a string of the response body.
* `SendAsync()` will give you a stream of the response body. Any stream type that is assignable from the base `Stream` type will work.
* Any other type will be treated as a JSON deserialization.