400 Bad Request when trying to query elasticsearch using HttpClient

Hi,

PostAsJsonAsync will serialise the object you pass to it as JSON, so in this case, it's serialising the JObject itself, which is not what you want here. There are a few solutions, but since you already have a string representing your JSON, you can send that as StringContent via the PostAsync method on HttpClient. Using strings for the request and response may not be the most optimal route for performance but will work fine with a few tweaks to your sample. Something like this should work:

public async Task<string> GetVirtualSupportAsync()
{
	var query = "{\"size\": 1000,\"query\": {\"bool\": {\"should\":[ {\"match\": { \"level\": \"Information\" } }, {\"match\": { \"level\": \"Error\" } } ], " +
				"\"filter\": [ { \"range\": { \"@timestamp\": { \"gte\": \"2021-07-26T07:58:45.304-05:00\", \"lt\": \"2021-07-26T08:58:45.305-05:00\" } } } ]," +
				"\"minimum_should_match\": 1 } } }";

	HttpClient client = new HttpClient();
	client.BaseAddress = new Uri("http://localhost:9200/");
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	HttpResponseMessage response = await client.PostAsync("customer-simulation-es-app-logs*/_search", new StringContent(query, Encoding.UTF8, "application/json"));

	if (response.IsSuccessStatusCode)
	{
		var contents = await response.Content.ReadAsStringAsync();
		Console.WriteLine(contents);
		return contents;
	}
	else
	{
		Console.WriteLine("{0} ({1}) \n {2}", (int)response.StatusCode, response.ReasonPhrase, response.RequestMessage);
		return response.ToString();
	}
}

Note that I also changed the code to use the async/await keywords as calling .Result in code can be problematic.

The response contents in this case will be the raw JSON string from the server, so you will then need to deserialise that or parse the data you require. To avoid a lot of this manual code, have you considered using our official .NET client library? This allows you to work with strongly-typed requests and responses, while also handling the HTTP transport and serialisation efficiently.