首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

WebService 數據交互深度解析:Wireshark 抓包還原 SOAP 封包結構

     編輯:關於C#

實驗環境

  • Server: IIS 託管 ASMX WebService (HelloWorld, add(int, int))
  • Client: .NET 呼叫產生的 Proxy (ISWSSoapClient)
  • 工具: Wireshark 過濾 (ip.addr eq 10.10.20.33 and ip.addr eq 192.168.0.100) and (tcp.port eq 1795 and tcp.port eq 8088)

完整交互流程 (TCP 層面)

  1. Client → Server: HTTP GET /WebService/IISWS.asmx (HTTP/1.1, Keep-Alive)
  2. Server → Client: ACK
  3. Client → Server: HTTP POST /WebService/IISWS.asmx + SOAP Envelope (含 add 請求, a=2, b=3)
  4. Server → Client: ACK
  5. Server → Client: HTTP 200 OK + SOAP Response (<addResult>5</addResult>)

SOAP 請求封包結構


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="https://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <add xmlns="https://tempuri.org/">
      <a>2</a>
      <b>3</b>
    </add>
  </soap:Body>
</soap:Envelope>

SOAP 回應封包結構


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope ...>
  <soap:Body>
    <addResponse xmlns="https://tempuri.org/">
      <addResult>5</addResult>
    </addResponse>
  </soap:Body>
</soap:Envelope>

嵌入式裝置 (Micro Framework) 實作啟示

MF 3.0 DPWS 難用,但掌握上述封包格式後,可在裝置端:

  1. 手工組裝 SOAP Envelope 字串 (含正確 Namespace、Action Header)。
  2. 使用 HttpWebRequest 發送 POST,設定 Content-Type: text/xml; charset=utf-8、SOAPAction Header。
  3. 解析回應 XML:XmlReader 逐節點讀取 (MF 無 XmlDocument),提取 <addResult> 文字內容。

關鍵技術難點

  • 命名空間處理:請求/回應的 Namespace 必須與 WSDL 定義完全一致,否則 Server 端無法路由到正確 WebMethod。
  • SOAPAction Header:ASMX 要求 SOAPAction: "https://tempuri.org/add",缺失會導致 400/500。
  • 編碼與換行:嚴格 UTF-8,避免 BOM、多餘空白字元。
  • 憑證/驗證:生產環境常需 HTTP Basic Auth、WS-Security、Client Cert,需在請求頭補充。

現代替代方案

新專案強烈建議採用 ASP.NET Core Web API (REST/JSON) 或 gRPC (Protobuf)。SOAP/XML 僅用於維護舊系統或對接強制標準的企業總線 (ESB)。

結語

透過 Wireshark 還原 SOAP 交互細節,是理解 WebService 底層協定、除錯跨平台互通、在受限裝置手工實作 Client 的核心技能。掌握封包結構,即掌握了互通的鑰匙。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved