0

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!

user687554
  • 10,663
  • 25
  • 77
  • 138
  • Possible duplicate of [Azure Search using REST c#](https://stackoverflow.com/questions/47214406/azure-search-using-rest-c-sharp) – vladimir Jul 17 '19 at 17:09

4 Answers4

2

The content type is a header of the content, not of the request, which is why this is failing. you can also set the content type when creating the requested content itself (note that the code snippet adds "application/json" in two places-for Accept and Content-Type headers)

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • You are wrong the *Content-Type* used for requests too - ["In requests, (such as POST or PUT), the client tells the server what type of data is actually sent."](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type). The *Content-Type*-header passed by *StringContent* - see [source code](https://github.com/steveharter/dotnet_corefx/blob/1b2b8e1262da221bf7c83c01b14df00618d5e4f1/src/System.Net.Http/src/System/Net/Http/StringContent.cs#L34). – vladimir Jul 17 '19 at 17:15
1

use this if you want to add any headers

 var apiClient = new HttpClient()
                    {
                      BaseAddress = new Uri(apiBaseURL)
                    };

var request = new HttpRequestMessage(HttpMethod.Post, "/api/controller/method");
request.Headers.Add("Accept", "application/json");
request.Headers.Add("api-key", mykey);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");

var response = apiClient.SendAsync(request).Result;
response.EnsureSuccessStatusCode();

Anurag
  • 78
  • 9
0

Did you see this tuto ?

Init HttpCLient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

POST your object

Product product = new Product
{
            Name = "Gizmo",
            Price = 100,
            Category = "Widgets"
};    
var url = await CreateProductAsync(product);

static async Task<Uri> CreateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PostAsJsonAsync(
        "api/products", product);
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34
0

Try this:

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
ArslanIqbal
  • 569
  • 1
  • 6
  • 19