Fluent wrapper around IHttpClientFactory
Install a NuGet package MyNihongo.FluentHttp
.
Add a section to IConfiguration
{
"FluentHttp": {
"BaseAddress": "https://jsonplaceholder.typicode.com",
"NtlmEnabled": false,
"Timeout": 100
}
}
Timeout
in seconds. forTimeout.Infinite
pass -1.
Register a service
using MyNihongo.FluentHttp;
services.AddFluentHttp();
// Or optionally configure the HTTP client
services.AddFluentHttp((services, httpClient) =>
{
// configure
});
To optimize JSON serialization JsonTypeInfo<T>
can be supplied for all methods. More info about these types here.
In further examples a variable IFluentHttp fluentHttp
will be used.
Gets a JSON stream.
[JsonSerializable(typeof(RecordContext[]))]
internal partial class RecordContext : JsonSerializerContext {}
public sealed record RecordContext
{
public int Id { get; set; }
}
// Get the model
var models = await fluentHttp
.AppendPathSegment("example")
.GetJsonAsync(RecordContext.Default.RecordArray, ct);
// When an API may return non-JSON values (e.g. `""`) this method can be used in order to ignore parsing exceptions
fluentHttp.GetJsonOrDefaultAsync(RecordContext.Default.RecordArray, ct);
Posts a JSON model and gets the JSON response.
[JsonSerializable(typeof(Request))]
internal partial class RequestContext : JsonSerializerContext {}
[JsonSerializable(typeof(Response))]
internal partial class ResponseContext : JsonSerializerContext {}
var req = new Request
{
Data = "example"
};
var response = await fluentHttp
.AppendPathSegment("example")
.PostJsonAsync(req, RequestContext.Default.Request, ResponseContext.Default.Response, ct);
// When an API may return non-JSON values (e.g. `""`) this method can be used in order to ignore parsing exceptions
fluentHttp.PostJsonOrDefaultAsync(req, RequestContext.Default.Request, ResponseContext.Default.Response, ct);
Fluent extensions supply additional parameters for the main HTTP methods.
Appends a new section to the request URI.
// get from https://jsonplaceholder.typicode.com/posts
var result = await fluentHttp
.AppendPathSegment("posts")
.GetJsonAsync<PostRecord>();
Appends multiple sections to the request URI.
// get from https://jsonplaceholder.typicode.com/posts/1/comments
var result = await fluentHttp
.AppendPathSegment("posts", "1", "comments")
.GetJsonAsync<PostCommentRecord>();
Appends a URL parameter
// get from https://jsonplaceholder.typicode.com/posts?value=123
var result = await fluentHttp
.AppendPathSegment("posts")
.AppendParameter("value", "123")
.GetJsonAsync<PostCommentRecord>();
Appends a header to the request.
var result = await fluentHttp
.AppendPathSegment("posts")
.WithHeader("my-header", "value")
.GetJsonAsync<PostRecord>();
Append the authentication header for the basic authentication
var result = await fluentHttp
.AppendPathSegment("posts")
.WithBasicAuth("username", "strong password")
.GetJsonAsync<PostRecord>();