A set of useful utilities for the .NET HttpClient.
Install-Package HttpClientGoodies
These small but useful utilities will make your HttpClient life worth living.
Here's an example of sending JSON content and reading JSON content in the least amount of code possible, while also providing Basic Authentication.
var dataToSend = new Todo {
Text = 'Install this package'
};
var createdTodo = await RequestBuilder.Post('http://api.todos.com/todos/{id}')
.BasicAuthentication("username", "password")
.AddUrlSegment("id", 123)
.JsonContent(dataToSend)
.SendAsync()
.AsJson<Todo>();
Console.WriteLine(createdTodo.Text);
Quite a lot! All methods that build the request are chainable! Let's asume the following for each snippet:
var builder = new RequestBuilder();
-
Headers:
builder.AddHeader("X-MyHeader", "cool value");
-
Query parameters
builder.AddQuery("searchText", "how do i get my girlfriend to tape her fingers together like a dinosaur");
-
Base URI + Resource URI separately
builder.BaseUri("http://todos.com") .ResourceUri("api/todos");
-
URL segments
builder.BaseUri("http://todos.com") .ResourceUri("api/todos/{id}") .AddUrlSegment("id", 123);
-
Authentication
builder.Authentication("Basic", "<some base64 here>"); // Basic auth shortcut (will base64 for you!) builder.BasicAuthentication("username", "password");
-
Setting content
builder.Content(new HttpStringContent("hehehe")); // Want to send JSON? builder.Content(new JsonContent(new Todo())); // Can do you one better! builder.JsonContent(new Todo());
-
HTTP method
builder.Method(HttpMethod.Get);
-
Getting the
HttpRequestMessage
to sendvar message = builder.ToHttpRequestMessage(); await someClient.SendAsync(message);
-
Sending the request without manually calling
ToHttpRequestMessage
var response = await builder.SendAsync(); // if you have a client instance you can pass it in. var response = await builder.SendAsync(client);
-
Reading content as JSON
var response = await builder.SendAsync(); var todo = await response.Content.ReadAsJsonAsync<Todo>(); // Even better... var todo = await builder.SendAsync().AsJson<Todo>(); // Custom settings? No problemo! var settings = new JsonSerializerSettings(); var todo = await response.Content.ReadAsJsonAsync<Todo>(settings); var todo = await builder.SendAsync().AsJson<Todo>(settings);
-
Shortcuts for methods
The following static methods are available:
Get
,Post
,Put
,Patch
,Delete
,Head
,Options
,Trace
.var todo = await RequestBuilder .Get('http://todos.com/api/todos/123') .SendAsync() .AsJson<Todo>();
Jeff Hansen - @Jeffijoe