【问题标题】:Sending SOAP message with C# Help Needed需要 C# 帮助发送 SOAP 消息
【发布时间】:2011-11-15 16:40:14
【问题描述】:

我想向 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();
        }
    }
}

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

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?)

任何帮助将不胜感激

【问题讨论】:

  • 您还没有具体说明问题所在。你有错误吗?错误是什么?它发生在哪里?当它发生时,相关对象的状态是什么?如果没有错误,代码的行为在什么时候会偏离预期的行为?
  • 如果 Web 服务没有 WSDL,那么您似乎在重新发明轮子。使用soap web 服务的常用方法是添加web 引用或使用wsdl.exe。这将创建代理类,为您处理所有的肥皂内容,您只需在类上调用方法即可。

标签: c# web-services soap


【解决方案1】:

您尝试使用的 Web 服务在 following address 处提供了一个 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>

【讨论】:

  • 嗨 Darin,我在 Visual Studio Web 参考下为我的项目添加了参考。它没有生成任何强类型类。我必须从 Visual Studio 命令提示符转到 Visual Studio 工具。创建了一个名为“PanelistService.cs”的 C# 文件。如 Rajesh 在第二个答案中所述,未创建任何配置文件。然后我将文件复制并粘贴到项目中。我现在收到以下错误:找不到类型或命名空间名称“RegistrationBindingsClient”(您是否缺少 using 指令或程序集引用?)
  • @user1048006,您应该使用“添加服务引用”对话框,而不是“添加 Web 引用”。为了使其可见,您的项目必须面向 .NET 3.0 或更高版本。如果您使用的是旧版本,您仍然可以通过向 WSDL 添加 Web 引用来调用 Web 服务。在这两种情况下,都会生成强类型类并自动添加到您的项目中。在第二种情况下,它们的名称可能不会与我的回答完全相同。您必须通过浏览生成的元数据来找到他们的名字。
  • 谢谢达林,这很好用。现在我面临获得响应的任务?任何想法将不胜感激。谢谢
【解决方案2】:

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

一些可能有用的链接:

【讨论】:

  • 谢谢大家,我会尝试你的建议并在这里报告我的发现。
【解决方案3】:

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

  1. 通过添加服务的 Web 引用。在 Visual Studio 中,您可以右键单击您的项目并选择“添加 Web 引用”选项,然后粘贴服务的 URL。

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

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

它将生成一个 .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

我的服务看起来像:

[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";
    }
}

【讨论】:

    【解决方案4】:

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

    重要免责声明:您应该只在您想要(或需要)手动发出基于 SOAP 的 Web 服务时使用它:在大多数常见场景中,您绝对应该将 Web 服务 WSDL 与添加服务参考 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;
            }
        }
    }
    

    有关此课程的更多信息和详细信息,您也可以在我的博客上read this post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2011-05-12
      • 2014-01-19
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多