执行 Delete httpclient 调用时获取无效的内容类型。我究竟做错了什么?

Getting Invalid Content Type doing a Delete httpclient call. What am I doing wrong?

当我尝试执行下面的代码时,它只会导致内容类型无效(错误编号 612)。

我正在尝试从静态列表中删除潜在客户 ID。我可以添加潜在客户 ID 或获取静态列表潜在客户。

我进行的 post 和 get 调用工作正常,尽管我进行的 post 调用似乎需要 url 字符串上的数据(如 $"{ endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}"; 如果我将 id 包含为 json 对象,它也会失败。这可能是什么线索我在删除调用时做错了。

string url = $"{endpointURL}/rest/v1/lists/{listID}/leads.json?id={leadID}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Authorization = new 
AuthenticationHeaderValue("Bearer", _access_token);
HttpResponseMessage response = await client.DeleteAsync(url);

此处的响应总是导致内容类型无效。

如果我在执行 deleteasync 调用之前添加此行,它甚至会在调用 deleteAsync 之前给我一个不同的错误。

client.DefaultRequestHeaders.Add("Content-Type", "application/json");

错误是"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."

像这样在您的代码中尝试使用 HttpRequestMessage

string url = $"{endpointURL}/rest/";
HttpClient client = new HttpClient
{
    BaseAddress = new Uri(url)
};

//I'm assuming you have leadID as an int parameter in the method signature
Dictionary<string, int> jsonValues = new Dictionary<string, int>();
jsonValues.Add("id", leadID);

//create an instance of an HttpRequestMessage() and pass in the api end route and HttpMethod
//along with the headers
HttpRequestMessage request = new HttpRequestMessage
    (HttpMethod.Delete, $"v1/lists/{listID}") //<--I had to remove the leads.json part of the route... instead I'm going to take a leap of faith and hit this end point with the HttpMethod Delete and pass in a Id key value pair and encode it as application/json
    {
        Content = new StringContent(new JavaScriptSerializer().Serialize(jsonValues), Encoding.UTF8, "application/json")
    };

request.Headers.Add("Bearer", _access_token);

//since we've already told the request what type of httpmethod we're using 
//(in this case: HttpDelete)
//we could just use SendAsync and pass in the request as the argument
HttpResponseMessage response = await client.SendAsync(request);

结果是解决方案结合了一些建议。

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, data);
// The key part was the line below
request.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

if (!string.IsNullOrEmpty(_access_token))
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _access_token);
}

HttpResponseMessage response = await client.SendAsync(request);

这对我有用。