用需要的c#帮助发送SOAP消息

本文关键字:SOAP 消息 帮助 | 更新日期: 2023-09-27 18:14:35

我想向Web服务发送一个SOAP消息并读取响应。我的代码如下:感谢您的帮助。

我希望我的问题不要重复,我已经四处寻找解决方案,但我没有成功。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Xml;
using System.Net;
using System.IO;
namespace TolunaPush
{
    public partial class _Default : System.Web.UI.Page
    {
        private string sourceID = "50001255";
        private string email = "adsvine@gmail.com";
        private string firstName = "Muz";
        private string lastName = "Khan";
        private string countryID = "2000077";
        private string countryLanguage = "2000240";
        private string postalCode = "N19 3NU";
        private string dob = "1977-03-08";
        private string gender = "2000247";
        protected void Page_Load(object sender, EventArgs e)
        {
            sendSoapMessage();
        }
        protected void sendSoapMessage()
        {
            XmlDocument doc = new XmlDocument();
            doc.InnerXml = @"<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>
                    <SubmitPanelist xmlns=""http://www.greenfield.com/RegistrationGateway/Messages"">
                      <Registration xmlns=""http://www.greenfield.com/RegistrationGateway/Types"">
                        <Source>
                          <SourceID>" + sourceID + @"</SourceID>
                        </Source>
                        <Email>" + email + @"</Email>
                        <FirstName>" + firstName + @"</FirstName>
                        <LastName>" + lastName + @"</LastName>
                        <CountryUK>
                          <CountryID>" + countryID + @"</CountryID>
                          <Language>" + countryLanguage + @"</Language>
                          <Address>
                            <Postalcode>" + postalCode + @"</Postalcode>
                          </Address>
                        </CountryUK>
                        <DOB>" + dob + @"</DOB>
                        <Gender>" + gender + @"</Gender>
                      </Registration>
                    </SubmitPanelist>
                  </soap:Body>
                </soap:Envelope>";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://coreg.surveycenter.com/RegistrationGateway/PanelistService.asmx");
            //if (proxy != null) req.Proxy = new WebProxy(proxy, true);
            // req.Headers.Add("GetClientInfo", "http://tempuri.org/GetClientInfo");
            req.ContentType = "text/xml;charset='"utf-8'"";
            req.Accept = "text/xml";
            req.Method = "POST";
            Stream stm = req.GetRequestStream();
            doc.Save(stm);
            stm.Close();
            WebResponse resp = req.GetResponse();
            stm = resp.GetResponseStream();
            StreamReader r = new StreamReader(stm);
            Response.Write(r.ReadToEnd());
            //Response.Write(stm.ToString());
            //Response.Write(r.ToString());
            Response.End();
        }
    }
}

更新正如Darin建议的那样。我按照指示做了,但是下面的代码行

using (var client = new RegistrationBindingsClient("RegistrationBindings"))

给出错误

The type or namespace name 'RegistrationBindingsClient' could not be found (are you missing a using directive or an assembly reference?)

如有任何帮助,不胜感激

用需要的c#帮助发送SOAP消息

您尝试使用的web服务在以下地址提供WSDL。因此,只需右键单击解决方案资源管理器中的引用,并使用Visual Studio中的添加服务引用对话框并指向WSDL,它将为您生成强类型类,以便轻松地使用服务,就像这样:

protected void sendSoapMessage()
{
    using (var client = new RegistrationBindingsClient("RegistrationBindings"))
    {
        var registration = new RegistrationType();
        registration.Source = new SourceType();
        registration.Source.SourceID = "50001255";
        registration.Email = "adsvine@gmail.com";
        registration.FirstName = "Muz";
        registration.LastName = "Khan";
        var countryUK = new CountryTypeUK();
        countryUK.CountryID = 2000077;
        countryUK.Language = 2000240;
        countryUK.Address = new AddressTypeUK();
        countryUK.Address.Postalcode = "N19 3NU";
        registration.Item = countryUK;
        registration.DOB = new DateTime(1977, 3, 8);
        registration.Gender = 2000247;
        client.SubmitPanelist(registration);
    }
}

看这有多容易。您不应该担心任何SOAP和XML管道。

如果您对使用以下请求在网络上发送的实际底层SOAP信封感兴趣:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <SubmitPanelist xmlns="http://www.greenfield.com/RegistrationGateway/Messages">
            <Registration xmlns="http://www.greenfield.com/RegistrationGateway/Types">
                <Source>
                    <SourceID>50001255</SourceID>
                </Source>
                <Email>adsvine@gmail.com</Email>
                <FirstName>Muz</FirstName>
                <LastName>Khan</LastName>
                <CountryUK>
                    <CountryID>2000077</CountryID>
                    <Language>2000240</Language>
                    <Income>0</Income>
                    <Education>0</Education>
                    <Address>
                        <Postalcode>N19 3NU</Postalcode>
                    </Address>
                </CountryUK>
                <DOB>1977-03-08</DOB>
                <Gender>2000247</Gender>
            </Registration>
        </SubmitPanelist>
    </s:Body>
</s:Envelope>

是否有任何错误消息或您使用了HTTP监视器?

一些可能有用的链接:

  • XmlDocument保存方法
  • 如何使用WebRequest类发送数据类似的问题在stackoverflow可能有帮助

您可以通过两种方法访问该服务:

  1. 通过添加服务的web引用。在visual studio中,你可以右键单击你的项目,选择Add Web reference选项,然后粘贴服务的URL。

  2. 在Visual studio命令提示符中使用wsdl工具从wsdl生成客户端代理。命令如下:

wsdl"http://coreg.surveycenter.com/RegistrationGateway/PanelistService.asmx?wsdl

c:>

它将生成一个.cs文件和一个output.config。在项目中包含.cs文件,您可以直接使用它来访问服务。确保配置文件条目被添加到您的项目配置中。

如果你想使用HttpWebRequest,然后找到下面的代码:

string soap = 
@"<?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>
    <Register xmlns=""http://tempuri.org/"">
      <id>123</id>
      <data1>string</data1>
    </Register>
  </soap:Body>
</soap:Envelope>";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");
req.Headers.Add("SOAPAction", "'"http://tempuri.org/Register'"");
req.ContentType = "text/xml;charset='"utf-8'"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
     using (StreamWriter stmw = new StreamWriter(stm))
     {
          stmw.Write(soap);
     }
}
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
// TODO: Do whatever you need with the response

My Service看起来像:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CustomerWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string Register(long id, string data1)
    {
        return "ID.CUSTOMER";
    }
}

这是一个通用类,你可以使用它来实现你需要的。

重要免责声明:您应该仅在希望(或需要)手动发出基于soap的web服务时使用此声明:在大多数常见场景中,您应该将web服务WSDL与Add service Reference Visual Studio特性一起使用,这是正确的方法。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
namespace Ryadel.Web.SOAP
{
    /// <summary>
    /// Helper class to send custom SOAP requests.
    /// </summary>
    public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        {
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var xmlStr = (useSOAP12)
                ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                      xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                      xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                      <soap12:Body>
                        <{0} xmlns=""{1}"">{2}</{0}>
                      </soap12:Body>
                    </soap12:Envelope>"
                : @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <soap:Body>
                           <{0} xmlns=""{1}"">{2}</{0}>
                        </soap:Body>
                    </soap:Envelope>";
            string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
            soapEnvelopeXml.LoadXml(s);
            // Create the web request
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction ?? url);
            webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset='"utf-8'"" : "text/xml;charset='"utf-8'"";
            webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
            webRequest.Method = "POST";
            // Insert SOAP envelope
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
            // Send request and retrieve result
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
    }
}

查看更多信息&关于这门课的细节,你也可以在我的博客上阅读这篇文章。