首页 > 后端开发 > C++ > 如何在 C# 中发送和接收 SOAP 请求和响应?

如何在 C# 中发送和接收 SOAP 请求和响应?

Susan Sarandon
发布: 2025-01-24 06:47:15
原创
260 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板