【问题标题】:HttpClient PutAsync to update a field using RestAPIHttpClient PutAsync 使用 RestAPI 更新字段
【发布时间】:2017-05-19 12:32:44
【问题描述】:

我们有一个第三方 API,它同时具有 GET 和 PUT 方法。第三方 API 返回响应并仅接受 XML。 api 看起来像 https://bh.org/api/v2/prj/A152 并返回 GET

<prj:prj uri="https://bh.org/api/v2/prj/V51" lid="V51" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:file="http://ge.com/ri/file" xmlns:prj="http://ge.com/ri/prj">
<name>fgfgfg</name>
<res uri="https://bh.org/api/v2/res/19"/>
<udf:type name="cis"/>
<udf:field type="String" name="ST">Cli</udf:field>
<udf:field type="String" name="CPN">TestName</udf:field>
<udf:field type="Numeric" name="No">1</udf:field>
<udf:field type="String" name="CA">Do not know</udf:field>
<udf:field type="String" name="Cto">Me</udf:field>
<udf:field type="String" name="Site">GT</udf:field>
</prj:prj>

我需要使用第三方 API 中的 put 方法将此处的名称从 ad-93 更改为 ABCD。我创建了应用程序,我们使用 GET 方法调用第三方 API 以获取响应

 using (var client_Name = new HttpClient())
 {
  ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  Uri uri = new Uri(BaseURL_C);
  client_Name.BaseAddress = uri;
  client_Name.DefaultRequestHeaders.Accept.Clear();
  client_Name.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
  client_Name.DefaultRequestHeaders.Authorization = new   System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray_C));

  string c_URL = BaseURL_C + "api/v2/prj/" + Name;
  var response_LabURL = client_Name.GetAsync(c_URL).Result;
  string responseString_URL = response_LabURL.Content.ReadAsStringAsync().Result;
  XDocument new_doc = XDocument.Parse(responseString_URL);
  new_doc.Descendants("name").FirstOrDefault().Value = serviceResponse;

使用上面的代码,我可以更改作为响应检索到的 XDocument 中名称的值。现在我正在尝试将 XDocument 作为参数传递给 putAsync 以使用 Rest API 更新字段。

 using (var putClient = new HttpClient())
 {
 var requestUrl = string c_URL = BaseURL_C + "api/v2/prj/" + Name;;
 using (HttpContent httpContent = new XDocument(new_doc))
  {
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
    HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
  }

但是上面的代码会抛出类似Cannot implicitly convert type 'System.Xml.Linq.XDocument' to 'System.Net.Http.HttpContent'的错误

我不确定如何将 XDocument new_doc 转换为 HtppContent 以便将它们作为参数传递。

【问题讨论】:

    标签: c# asp.net linq api asp.net-web-api


    【解决方案1】:

    你必须像这样使用它

    HttpContent httpContent = new StringContent(new_doc.ToString(), Encoding.UTF8, "application/xml");
    

    并删除该行

    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2017-08-03
      相关资源
      最近更新 更多