Fluent wrapper around IHttpClientFactory
$ dotnet add package MyNihongo.FluentHttpFluent wrapper around IHttpClientFactory
Install a NuGet package MyNihongo.FluentHttp.
Add a section to IConfiguration
{
"FluentHttp": {
"BaseAddress": "https://jsonplaceholder.typicode.com",
"NtlmEnabled": false
}
}
Register a service
using MyNihongo.FluentHttp;
services.AddFluentHttp();
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);
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);
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 header to the request.
var result = await fluentHttp
.AppendPathSegment("posts")
.WithHeader("my-header", "value")
.GetJsonAsync<PostRecord>();