我正在尝试将一些数据发布到Azure REST API。我在Postman中定义了一个有效的请求。现在,在我的C#代码中,我想使用HttpClient
而不是帮助程序库。为了做到这一点,我目前有:
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);
}
运行此命令时,会抛出一个InvalidOperationException
,内容为:
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
我不明白自己做错了什么。如何使用C#中的HttpClient
将数据发布到Azure REST API?
谢谢!
答案 0 :(得分:1)
内容类型是内容的标头,而不是请求的标头,这就是失败的原因。您还可以在创建请求的内容本身时设置内容类型(请注意,代码段在两个位置(用于Accept和Content-Type标头)添加了“ application / json”)
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT
答案 1 :(得分:0)
您看到这个tuto吗?
初始化HttpCLient
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
发布您的对象
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;
}
答案 2 :(得分:0)
如果要添加任何标题,请使用此
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();
答案 3 :(得分:0)
尝试一下:
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");