I use .NET 6, and I want to use HttpClient.GetAsync to send a query. One of the arguments is JSON, and I do not know how to encode it correctly.
Here is the documentation I use: https://docs.datadoghq.com/api/latest/metrics/#query-timeseries-points
I have tried with this method, but I got a BAD REQUEST from the server
public async Task<string> MetricAggregateAsync(string from, string to, string query)
{
AddDDApiKey();
AddDDApplicationKey();
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//System.Web.Helpers.Json.Encore(query);
query = System.Web.HttpUtility.UrlEncode(query);
string content = "?from=" from "&to=" to "&query=" query;
HttpResponseMessage response = await _httpClient.GetAsync("v1/query" content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
CodePudding user response:
From the documentation you shared (thanks for that!) it seems like this GET /query
endpoint does not expect a JSON content at all. Try this version of your code:
public async Task<string> MetricAggregateAsync(string from, string to, string query)
{
AddDDApiKey();
AddDDApplicationKey();
query = System.Web.HttpUtility.UrlEncode(query);
string url = $"v1/query?from={from}&to={to}&query={query}";
HttpResponseMessage response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
By the way, there are some tricks you could employ:
- You could remove those
calls inAddDDApiKey() AddDDApplicationKey()
MetricAggregateAsync
(and all other methods that consume this API) if you configured your_httpClient
to include some headers in all requests it sends, e.g.:
This should be done in the same place where that_httpClient.DefaultRequestHeaders.Add("DD-API-KEY", "TODO"); _httpClient.DefaultRequestHeaders.Add("DD-APPLICATION-KEY", "TODO");
_httpClient
is instantiated (not inMetricAggregateAsync
). - A safer way to build URL strings would be to replace
withquery = System.Web.HttpUtility.UrlEncode(query); string url = $"v1/query?from={from}&to={to}&query={query}";
var urlParameters = System.Web.HttpUtility.ParseQueryString(""); // Strange way to start, but please bear with it :) urlParameters.Add("from", from); urlParameters.Add("to", to); urlParameters.Add("query", query); // Automatically encodes URL, so you don't have to do it manually string url = $"v1/query?{urlParameters}";