简体   繁体   中英

C# - Set HttpClient Headers to POST data to Azure REST API

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!

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

尝试这个:

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

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;
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM