调用Ebay API时,Content-Language标头会引发Misused标头名称错误

时间:2018-10-30 13:55:28

标签: c# rest http-headers dotnet-httpclient ebay-api

当我使用Ebay API向CreateOrReplaceInventoryItem发出PUT请求时,出现此错误:

  

标题名称滥用。确保请求标头与   HttpRequestMessage,带有HttpResponseMessage的响应标头和   带有HttpContent对象的内容标题。

下面的代码引发错误。

using (var client = new HttpClient())
{
    var baseUri = new Uri(string.Format("https://api.sandbox.ebay.com/sell/inventory/v1/inventory_item/{0}", SKU));
    client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));
    client.DefaultRequestHeaders.Add("Content-Language", "en-US");

    var payload = JsonConvert.SerializeObject(product);
    var content = new StringContent(payload, Encoding.UTF8, "application/json");

    var response = client.PutAsync(baseUri, content).Result;
    return response.Content.ReadAsStringAsync().Result;
}

如果我删除该行:

client.DefaultRequestHeaders.Add("Content-Language", "en-US");

然后我得到一个返回的错误对象:

errors":[{"errorId":25709,"domain":"API_INVENTORY","subdomain":"Selling","category":"REQUEST","message":"Invalid value for header Content-Language."}]} 

我在做什么错?还有另一种我不知道的设置内容语言的方法吗?

1 个答案:

答案 0 :(得分:1)

由于Content-Language是内容标头,因此应在HttpContent实例而不是DefaultRequestHeaders中分配它。根据您的代码将是这样的:

using (var client = new HttpClient())
{
    var baseUri = new Uri(string.Format("https://api.sandbox.ebay.com/sell/inventory/v1/inventory_item/{0}", SKU));
    client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", token));

    var payload = JsonConvert.SerializeObject(product);
    var content = new StringContent(payload, Encoding.UTF8, "application/json");
    content.Headers.Add("Content-Language", "en-US");

    var response = client.PutAsync(baseUri, content).Result;
    return response.Content.ReadAsStringAsync().Result;
}