5 c# httpclient request asp.net-web-api
我对这段代码有疑问,我的目标是通过 API 发送修改,所以我正在执行requestover HttpClient。
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
public class patchticket
{
public string patch(string ticketid)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://desk.zoho.com/api/v1/tickets/"+ticketid))
{
request.Headers.TryAddWithoutValidation("Authorization", "6af7d2d213a3ba5e9bc64b80e02b000");
request.Headers.TryAddWithoutValidation("OrgId", "671437200");
request.Content = new StringContent("{\"priority\" : \"High\"}", Encoding.UTF8, "application/x-www-form-urlencoded");
var response = httpClient.SendAsync(request);
return response
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果是我没有任何错误,但更改没有生效。
凭据没问题,我已经用相同参数的curl对其进行了测试,效果很好。
Fel*_*ani 10
看起来您想json在请求中发布 a 。尝试定义正确的内容类型,即application/json. 对于样品:
request.Content = new StringContent("{\"priority\" : \"High\"}",
Encoding.UTF8,
"application/json");
Run Code Online (Sandbox Code Playgroud)
由于您的方法返回一个string它可以是一个非异步方法。该方法SendAsync是异步的,您必须等待请求完成。Result您可以尝试在提出要求后致电。对于样品:
var response = httpClient.SendAsync(request).Result;
return response.Content; // string content
Run Code Online (Sandbox Code Playgroud)
你将得到一个HttpResponseMessage对象。关于其响应,有很多有用的信息。
无论如何,由于它是 IO 绑定操作,所以最好使用异步版本,如下所示:
var response = await httpClient.SendAsync(request);
return response.Content; // string content
Run Code Online (Sandbox Code Playgroud)