Here is an simple console program example with HttpClient doing a GET request.
using ServiceStack;
using var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://web.web-templates.io/hello/world");
httpRequestMessage.With(config =>
{
config.Accept = "application/json";
config.UserAgent = "MyCustomAgent/1.0";
});
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Console.WriteLine($"Response: {responseBody}");
Another performing a post:
using System.Text;
using ServiceStack;
using ServiceStack.Text;
using var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://web.web-templates.io/hello");
var payload = new { Name = "world" };
var payloadString = JsonSerializer.SerializeToString(payload);
httpRequestMessage.Content = new StringContent(payloadString, Encoding.UTF8);
httpRequestMessage.With(config =>
{
config.ContentType = "application/json";
config.Accept = "application/json";
});
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Console.WriteLine($"Response: {responseBody}");
If you aren’t using HttpClient, the same can be used to configure HttpWebRequest:
So you can use your cfg in the With action to configure the options.
The https-utils page shows examples used with other extension methods like GetJsonFromUrlAsync where the requestFilter action is supplying the HttpWebRequest or HttpRequestMessage in with the interchangeable .With actions are used:
So the same type of request code can be reduced quite a bit to this simplified form for common use cases where your requestFilter action code might be common.