首頁 > 後端開發 > C++ > 如何在 C# 中發送和接收 SOAP 請求和回應?

如何在 C# 中發送和接收 SOAP 請求和回應?

Susan Sarandon
發布: 2025-01-24 06:47:15
原創
299 人瀏覽過

How to Send and Receive SOAP Requests and Responses in C#?

在 C 中發送 SOAP 請求並接收回應

問題

您需要建立 C# 用戶端,用於向 Web 服務發送 SOAP請求並接收這

解決方案

以下程式碼片段示範如何實現此目的:

using System.Net;
using System.IO;
using System.Xml;

public static void CallWebService()
{
    // Replace with your SOAP endpoint URL
    var url = "http://example.com/service.asmx";
    // Replace with your SOAP action
    var action = "http://example.com/service.asmx?op=HelloWorld";

    var soapEnvelope = CreateSoapEnvelope();
    var webRequest = CreateWebRequest(url, action);
    InsertSoapEnvelopeIntoWebRequest(soapEnvelope, webRequest);

    // Send the SOAP request
    var asyncResult = webRequest.BeginGetResponse(null, null);
    asyncResult.AsyncWaitHandle.WaitOne();

    // Receive the SOAP response
    var soapResponse = "";
    using (var webResponse = webRequest.EndGetResponse(asyncResult))
    {
        using (var reader = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResponse = reader.ReadToEnd();
        }
    }
}

private static HttpWebRequest CreateWebRequest(string url, string action)
{
    var webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    return webRequest;
}

private static XmlDocument CreateSoapEnvelope()
{
    var soapEnvelope = new XmlDocument();
    soapEnvelope.LoadXml(
        $@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""
               xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" 
               xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
          <SOAP-ENV:Body>
            <HelloWorld xmlns=""http://tempuri.org/""
                SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
                <int1 xsi:type=""xsd:integer"">12</int1>
                <int2 xsi:type=""xsd:integer"">32</int2>
            </HelloWorld>
          </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>");
    return soapEnvelope;
}

private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelope, HttpWebRequest webRequest)
{
    using (var stream = webRequest.GetRequestStream())
    {
        soapEnvelope.Save(stream);
    }
}
登入後複製

此程式碼建立一個Web 請求,設定SOAP 操作標頭,然後插入將SOAP 信封放入請求中。然後它發送請求並讀取 SOAP 回應。

以上是如何在 C# 中發送和接收 SOAP 請求和回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板