Home > Mobile >  .NET 6 - Pass JSON in query string
.NET 6 - Pass JSON in query string

Time:03-10

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:

  1. You could remove those
    AddDDApiKey()
    AddDDApplicationKey()
    
    calls in 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.:
    _httpClient.DefaultRequestHeaders.Add("DD-API-KEY", "TODO");
    _httpClient.DefaultRequestHeaders.Add("DD-APPLICATION-KEY", "TODO");
    
    This should be done in the same place where that _httpClient is instantiated (not in MetricAggregateAsync).
  2. A safer way to build URL strings would be to replace
    query = System.Web.HttpUtility.UrlEncode(query);
    
    string url = $"v1/query?from={from}&to={to}&query={query}";
    
    with
    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}";
    
  • Related