I am trying to post some data to an Azure REST API. I have a request defined in Postman that works. Now, in my C# code, I want to use the HttpClient
instead of the helper libraries. In an attempt to do this, I currently have:
try
{
var json = @"{
'@search.action':'upload',
'id':'abcdef',
'text':'this is a long blob of text'
}";
using (var client = new HttpClient())
{
var requestUri = $"https://my-search-service.search.windows.net/indexes/my-index/docs/index?api-version=2019-05-06";
// Here is my problem
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("api-key", myKey);
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
using (var content = new StringContent(json, Encoding.UTF8, "application/json")
{
using (var request = Task.Run(async() => await client.PostAsync(requestUri, content)))
{
request.Wait();
using (var response = request.Result)
{
}
}
}
}
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
When I run this, an InvalidOperationException
gets thrown that says:
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
I don't understand what I've done wrong. How do I post data to an Azure REST API using the HttpClient
in C#?
Thank you!