Skip to content

Classes and extension methods to make easier to work with REST APIs via HttpClient

License

Notifications You must be signed in to change notification settings

Madmike614/HttpExtensions

 
 

Repository files navigation

Kralizek's HTTP Extensions

Overview

This repository contains a set of extensions to ease working with HTTP requests and response in .NET.

Kralizek.Extensions.Http

This package offers basic HTTP utilities.

Query string

The HttpQueryStringBuilder class helps creating a valid query string using the same methodology of the StringBuilder.

var builder = new HttpQueryStringBuilder();

builder.Add("foo", "bar");
builder.Add("hello", "world");
builder.Add("asd", "lol");

string query = builder.BuildQuery();

Console.WriteLine(query);  // asd=lol&foo=bar&hello=world

The BuildQuery method offers the possibility of collating items with the same key with a separator.

var builder = new HttpQueryStringBuilder();

builder.Add("fields", "firstName");
builder.Add("fields", "lastName");

var query = builder.BuildQuery(collateKeysBy: ",");

Console.WriteLine(query);  // fields=firstName,lastName

Kralizek.Extensions.Http.Json

This package offers support for JSON payloads.

JSON payloads

The JsonContent class inherits from System.Net.Http.HttpContent, therefore it can be used to attach JSON payloads to an HTTP request.

The static factory method FromObject<T> accepts any object and uses Newtonsoft.Json to serialize it into a JSON object.

var person = new Person
{
    FirstName = "John",
    LastName = "Doe"
};

using var request = new HttpRequestMessage(HttpMethod.Post, "http://localtest.me:8080") 
{
    Content = JsonContent.FromObject(person)
};

using var response = await http.SendAsync(request);

HTTP REST Client

The HttpRestClient is an opinionated wrapper around the HttpClient.

Here are some advantages of using the HttpRestClient:

  • it delegates the HttpClient instance management to IHttpClientFactory,
  • offers methods to send HTTP requests with and without payload expecting or not a payload in the response,
  • it embeds logging using the Microsoft.Extensions.Logging framework,
  • it automatically handles serialization and deserialization to and from JSON payloads,
  • it integrates nicely with the Microsoft.Extensions.DependencyInjection framework.

Here is a sample of its usage.

var client = services.GetRequiredServices<IHttpRestClient>();

var person = await client.SendAsync<Person>(HttpMethod.Get, "/people/1", query);

In the snippet above, the call to the SendAsync method takes care of:

  • getting an instance of HttpClient from the local IHttpClientFactory,
  • assemble the HTTP request using the specified HTTP method, the path and the query from the previous snippet,
  • log the HTTP request,
  • send the HTTP request,
  • receive the HTTP response,
  • log the HTTP response,
  • validate the result of the request via the status code of the HTTP response,
  • deserialize the payload into an instance of the Person class,
  • dispose all the resources that need disposing (HttpRequestMessage and HttpResponseMessage)

Setup

In the package there are different utilities that allow a simple yet powerful setup of the HttpRestClient.

services.AddHttpRestClient("RequestBin", builder => builder
    .ConfigureHttpClient(http =>
    {
        http.BaseAddress = new Uri("https://your-pipe.x.pipedream.net");
        http.DefaultRequestHeaders.Add("X-Test", "This is a test");
    })
    .ConfigureHttpRestClient(options =>
    {
        options.ContentMediaType = JsonContent.ApplicationJsonMediaType;
    })
    .ConfigureSerialization(json => 
    {
        json.ContractResolver = new DefaultContractResolver 
        {
            NamingStrategy = new CamelCaseNamingStrategy()
        };

        json.Formatting = Formatting.Indented;
    }));

Since AddHttpRestClient accepts a delegate of type Action<IHttpClientBuilder>, you can leverage extensions to the HttpClientFactory API like Polly.

Versioning

This library follows Semantic Versioning 2.0.0 for the public releases (published to the nuget.org).

How to build

This project uses Cake as a build engine. You will also need the .NET Core SDK 3.1.401.

If you would like to build this project locally, just execute the build.cake script.

You can do it by using the .NET tool created by CAKE authors and use it to execute the build script.

dotnet tool restore
dotnet cake

About

Classes and extension methods to make easier to work with REST APIs via HttpClient

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%