Request Overview
HttpBuildR.Request is a set of extension methods that build a
HttpRequestMessage. Nothing is wrapped, the result is the
core type.
dotnet add package HttpBuildR.Request
using HttpBuildR;
using Req = HttpMethod;
With
implicit usings
the using HttpBuildR; line is not needed.
Start with a method and a url
To takes a string or a Uri, and an optional http
version:
HttpRequestMessage request = HttpMethod.Get.To("https://example.com");
GET https://example.com/ HTTP/2.0
Add headers
WithHeader takes any header. The typed helpers in the headers guide cover the standard ones.
request = request.WithHeader("X-Request-Id", "abc-123");
GET https://example.com/ HTTP/2.0
X-Request-ID: abc-123
Headers are normalised by System.Net.Http, so X-Request-Id comes back as
X-Request-ID.
Add content
Content helpers replace any existing content:
request = HttpMethod.Post.To("https://example.com/widgets")
.WithJsonContent(new { Name = "Ben", Age = 36 });
POST https://example.com/widgets HTTP/2.0
Content-Type: application/json; charset=utf-8
{"Name":"Ben","Age":36}
Text, xml, form url encoded and raw stream content are all available, see the content guide.
Send it
The builder stops at the request. Sending is still the caller's job:
using HttpClient client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
See also
- Request Headers - every header helper
- Request Content - every content helper
- Response Overview - the same pattern for responses