Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET HttpClient add query string and JSON body to POST

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

like image 280
Kevin R Avatar asked Oct 27 '16 17:10

Kevin R


1 Answers

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);
like image 75
Kevin R Avatar answered Oct 01 '22 19:10

Kevin R