使用C#Help发送SOAP消息

我想将SOAP消息发送到Web服务并读取响应。 我的代码如下:我将非常感谢您的帮助。

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

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 = @"     " + sourceID + @"  " + email + @" " + firstName + @" " + lastName + @"  " + countryID + @" " + countryLanguage + @" 
" + postalCode + @"
" + dob + @" " + gender + @" "; 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。 因此,只需右键单击解决方案资源管理器中的“引用”,然后使用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信封感兴趣:

      50001255  adsvine@gmail.com Muz Khan  2000077 2000240 0 0 
N19 3NU
1977-03-08 2000247

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

一些可能有用的链接:

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

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

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

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

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

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

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

 string soap = @"    123 string   "; 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"; } } 

这是一个通用课程,您可以用它来实现您的需求。

重要免责声明 :您只应在需要(或需要)手动发布基于SOAP的Web服务时使用此选项:在大多数常见场景中,您绝对应将Web Service WSDL与Add Service Reference Visual Studiofunction一起使用,即这样做的正确方法。

 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Xml; namespace Ryadel.Web.SOAP { ///  /// Helper class to send custom SOAP requests. ///  public static class SOAPHelper { ///  /// Sends a custom sync SOAP request to given URL and receive a request ///  /// The WebService endpoint URL /// The WebService action name /// A dictionary containing the parameters in a key-value fashion /// The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter) /// Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default) /// A string containing the raw Web Service response public static string SendSOAPRequest(string url, string action, Dictionary parameters, string soapAction = null, bool useSOAP12 = false) { // Create the SOAP envelope XmlDocument soapEnvelopeXml = new XmlDocument(); var xmlStr = (useSOAP12) ? @"   <{0} xmlns=""{1}"">{2}  " : @"   <{0} xmlns=""{1}"">{2}  "; string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}", 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; } } } 

有关此课程的其他信息和详细信息,您还可以在我的博客上阅读此文章 。