Base 64 字段,包含要传递给 WebService 的文件信息

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

我需要将 zip 文件传递到 byte[] 类型的目标文件。 我对网络服务非常陌生。

我用 C# 代码编写了以下内容:

string encodedStr = Utf16ToUtf8(@"c:\Users\joshepjohn\Test.zip");
            byte[] bytes = Encoding.UTF8.GetBytes(encodedStr);
            string base64 = EncodeToBase64(encodedStr);
            request.message = System.Convert.FromBase64String((base64));

该网络服务的文档说: request.message = 包含要导入的文档数据的文件。这是您要导入到域的文件本身。 该文件将以 ZIP 格式压缩。在 SOAP 消息中,Base64 编码的 ZIP 文件数据将在 SOAP 调用的信封内发送。

我对 SOAP 消息感到困惑。除了 C# 之外,我还需要使用其他东西吗? 上面的代码是否适合用于文档目的?.

我尝试过,但网络服务发送一条消息:尚未导入文件。

我希望将zip文件导入到网络服务中。

c# file web-services publish
1个回答
0
投票

要在 C# 中将 zip 文件作为 Base64 编码的 SOAP 消息传递,您需要执行以下步骤:

  • 使用 File.ReadAllBytes 方法将 zip 文件读取为字节数组。

  • 使用以下命令将字节数组转换为 Base64 字符串 Convert.ToBase64String 方法。

  • 使用 XML 文档或字符串生成器创建 SOAP 消息。你 可以使用与以下内容匹配的模板或 SOAP 消息示例 网络服务规范。你可以找到一些 SOAP 的例子 网络搜索结果中的消息。

  • 将base64字符串插入到SOAP消息体中,其中 request.message 元素是预期的。您可以使用 XmlDocument 或 XDocument 类来操作 XML 元素,或者您可以使用 字符串连接或插值以插入 base64 字符串 进入消息。

  • 使用 HttpClient 或 WebClient 对象。您可以使用 PostAsync 或 UploadString 方法 发送消息并获取回复。

以下是遵循以下步骤的 C# 代码示例:

// Read the zip file as a byte array 
byte[] bytes = File.ReadAllBytes(@“c:\Users\joshepjohn\Test.zip”);

// Convert the byte array to a base64 string 
string base64 = Convert.ToBase64String(bytes);

// Create a SOAP message using a string builder 
StringBuilder soapMessage = new StringBuilder(); soapMessage.Append(“<?xml version="1.0" encoding="utf-8"?>”); soapMessage.Append(“<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/">”); soapMessage.Append(“soap:Body”); soapMessage.Append(“<request xmlns="http://www.example.com/webservice">”); soapMessage.Append(“<message>”); 

// This is where the base64-encoded zip file data goes     
soapMessage.Append(base64); 

// Insert the base64 string             
soapMessage.Append(“</message>”); soapMessage.Append(“</request>”); 
soapMessage.Append(“</soap:Body>”); soapMessage.Append(“</soap:Envelope>”);

// Send the SOAP message to the web service using an HttpClient 
HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add(“SOAPAction”, “http://www.example.com/webservice/import”); 

// This may vary depending on the web service 
HttpContent content = new StringContent(soapMessage.ToString(), Encoding.UTF8, “text/xml”); HttpResponseMessage response = await client.PostAsync(“http://www.example.com/webservice.asmx”, content); 

// This is the web service URL 
string responseString = await response.Content.ReadAsStringAsync(); 

// This is the web service response
© www.soinside.com 2019 - 2024. All rights reserved.