0

I want to pass a query string to the request,

if I type it on the request itself works, however if I add it to the request.Content it fails,

Here's my code

 public async Task<Product> GetProducts(
        IEnumerable<string> products,
        DateTime startDate,
        DateTime endDate)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(this.productDataAddress);
        client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var request = new HttpRequestMessage(HttpMethod.Get, "/products/datetime");
        request.Headers.Add("apad-accept", "application/json");

        request.Content = new StringContent(
            "{\"productIds\":\"PR00001\"}",
            Encoding.UTF8,
            "application/json");

        var response = await client.SendAsync(request);

        var content = await response.Content.ReadAsStringAsync();

        var result = JsonConvert.DeserializeObject<Product>(content);

        return result;
    }

if I amend the line var request = new HttpRequestMessage(HttpMethod.Get, "/products/datetime?productIds=PR00001");it works

I have google it but doesn't work, any ideas of how to build the query string?

Thanks

Garry A
  • 103
  • 9
  • this is the query string: `/products/datetime?productIds=PR00001")`. A query string is taken from the `url`. - (https://stackoverflow.com/questions/724526/how-to-pass-multiple-parameters-in-a-querystring) – Ryan Wilson Nov 02 '20 at 13:51
  • I agree, but can we pass it to the request like a json or else? something like request.Content = new StringContent( "{\"productIds\":\"PR00001\"}", Encoding.UTF8, "application/json"); – Garry A Nov 02 '20 at 13:54
  • Of course your can pass it as `Content`, but it would no longer be getting it as `query string`, you would be taking it as a `Post` or `Put` request and deserializing the body of the request. – Ryan Wilson Nov 02 '20 at 13:55
  • Perhaps this will clarify my previous comment: (https://stackoverflow.com/questions/978061/http-get-with-request-body#:~:text=Yes.,messages%20with%20that%20in%20mind.&text=The%20requirements%20on%20parsing%20are,never%20useful%20to%20do%20so.) – Ryan Wilson Nov 02 '20 at 14:01

0 Answers0