简体   繁体   English

C#-设置HttpClient标头以将数据发布到Azure REST API

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

I am trying to post some data to an Azure REST API. 我正在尝试将一些数据发布到Azure REST API。 I have a request defined in Postman that works. 我在Postman中定义了一个有效的请求。 Now, in my C# code, I want to use the HttpClient instead of the helper libraries. 现在,在我的C#代码中,我想使用HttpClient而不是帮助程序库。 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: 当我运行此命令时,将抛出InvalidOperationException

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#? 如何使用C#中的HttpClient将数据发布到Azure REST API?

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) 您还可以在创建请求的内容本身时设置内容类型(请注意,代码段在两个位置(用于Accept和Content-Type标头)添加了“ application / json”)

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT

尝试这个:

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

Did you see this tuto ? 你看到这个芭蕾舞裙了吗?

Init HttpCLient 初始化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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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