Extensions and utilities for System.Net.Http.HttpClient
on .NET and .NET Core.
- Typed extensions for
HttpClient
- Synchronous extensions for
HttpClient
JsonContent<TEntity>
for easy JSON serialization
GET
/POST
/PUT
/DELETE
of standard .NET objects using DataContractJsonSerializer
. (Optional: Supports data contract annotations.)
Declare a model:
[DataContract]
public class Thing
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string SomeProperty { get; set; }
}
Import extensions:
using DotNetLiberty.Http;
Create client:
var client = new HttpClient()
.WithBaseUri(new Uri("http://localhost:5000/api/things/"))
.AcceptJson();
IEnumerable<Thing> things = await client.GetManyAsync<Thing>();
Thing thing = await client.GetSingleAsync<Thing>(1);
Thing created = await client.PostAsync(new Thing {
SomeProperty = "Some value"
});
Thing updated = await client.PutAsync(1, new Thing {
Id = 1,
SomeProperty = "Some value"
});
await client.DeleteAsync(1);
System.Net.Http.HttpClient
only supports asynchronous variants of operations out of the box. Rather than handle Wait
ing and unpacking exceptions we can use synchronous extension methods.
Import extensions:
using DotNetLiberty.Http.Sync;
Create client:
var client = new HttpClient()
.WithBaseUri(new Uri("http://localhost:5000/"));
HttpResponseMessage response = client.Get("");
HttpResponseMessage response = client.Post("", new StringContent(""));
HttpResponseMessage response = client.Put("", new StringContent(""));
HttpResponseMessage response = client.Delete("");
var request = new HttpRequestMessage();
HttpResponseMessage response = client.Send(request);
Rather than having to serialize and encode your entities into a StringContent
instance manually, you can use a JsonContent<TEntity>(TEntity)
instead.
Thing thing = new Thing {
Id = 1,
SomeProperty = "Some value"
};
StringContent content = new JsonContent<Thing>(thing);
HttpResponseMessage response = await client.PostAsync("", content);
.NET Liberty - http://dotnetliberty.com