使用 HttpClient 和 C# 在 post 请求上发送 json

问题描述 投票:0回答:1

我对这段代码有疑问,我的目标是通过 API 发送修改,所以我在

request
上做了
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

           }
       }

   }
}

结果是我没有任何错误,但是更改没有生效。

凭证没问题,我用相同参数的curl测试过它,效果很好。

c# api asp.net-web-api request httpclient
1个回答
10
投票

您似乎想在请求中发布

json
。尝试定义正确的内容类型,即
application/json
。样品:

request.Content = new StringContent("{\"priority\" : \"High\"}",
                                    Encoding.UTF8, 
                                    "application/json");

由于您的方法返回

string
,因此它可以是非异步方法。方法
SendAsync
是异步的,您必须等待请求完成。您可以尝试在请求后致电
Result
。样品:

var response = httpClient.SendAsync(request).Result;
return response.Content; // string content

你会得到一个HttpResponseMessage的对象。上面的回复有很多有用的信息。

无论如何,由于它是 IO 绑定操作,所以最好使用像这样的异步版本:

var response = await httpClient.SendAsync(request);
return response.Content; // string content
© www.soinside.com 2019 - 2024. All rights reserved.