如何使用 C# 将 XML 输入传递给 API 调用

How to pass XML input to API call using C#

我有以下 XML 输入。我需要调用 API 并将其作为输入传递,但值会动态变化。如何构建此输入结构?

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Test xmlns="http://tempuri.org/">
      <acc>test</acc>
      <pass>abc</pass>
      <xmlInvData>
<![CDATA[
<MyData>
    <name>test</name>  
    <number>900</number>
</MyData>
]]>
</xmlInvData>
      <username>test</username>
      <password>123</password>    
    </Test>
  </soap:Body>
</soap:Envelope>

我在 C# 中有 MyData Class,这对设置 namenumber 值很有用。

但是我怎样才能形成一个完整的结构并传递给Api调用呢? soap:Envelop 和皂体?

HttpClient httpClient = new HttpClient();

                string requestUri = "https://testurl";

                var byteArray = Encoding.ASCII.GetBytes("username:password");

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                HttpResponseMessage response = await httpClient.PostAsync(requestUri, httpContent);

我需要了解如何按照我的输入 json.

形成 httpContent

假设您已经构建了数据结构并将其序列化为名为 xml:

的字符串
var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");