How do I set up a .NET HttpClient.SendAsync() request to contain query string parameters and a JSON body (in the case of a POST)?
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// How do I add the queryString?
// Send the request
client.SendAsync(request);
Every example I've seen says to set the
request.Content = new FormUrlEncodedContent(queryString)
but then I lose my JSON body initialization in the request.Content
I ended up finding Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()
that was what I needed. This allowed me to add the query string parameters without having to build the string manually (and worry about escaping characters and such).
Note: I'm using ASP.NET Core, but the same method is also available through Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()
New code:
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
// This is the missing piece
var requestUri = QueryHelpers.AddQueryString("something", queryString);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// Send the request
client.SendAsync(request);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With