简体   繁体   中英

How do I programmatically send information to a web service in C# with .NET?

I know this sort of counts as reinventing the wheel here, but I need to know to communicate with a web service through http/soap/xml and web messages. The reason is I need to communicate with a third party web service for work, but there is something wrong with the WSDL or something and it does not work when connecting to it with the .NET wizard.

So, can anyone give me a process/simple example/etc. of how to do this or can anyone give me a link to somewhere that explains it? I'm not very savvy with web requests and responses.

How do I construct and send the request? How do I parse the response?

Here is the code for a simple web service. Pretend the address of the .asmx is "http://www.mwebb.com/TestSimpleService.asmx":

using System;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace TestSimpleService
{
    [WebService]
    public class Soap : System.Web.Services.WebService
    {
        [WebMethod]
        public string SayHello(string name)
        {
            return "Hello " + name + "!";
        }
    }
}

How would I call this method?

Any help is appreciated.

I really just want to know how to send the data to the web service. I can get all of the method/SOAP action/URL data and I can parse the response data. I just don't know what objects to use or how to use them.

If anyone knows of a few simple .NET soap clients like SUDS in Python, that would help too.

If you want to communicate directly, I'd look into using an HTTPWebRequest as ultimately a webservice call is just XML sent using an HTTP POST.

The following link has some examples: http://geekswithblogs.net/marcel/archive/2007/03/26/109886.aspx

As a way of testing the external webservice before contacting it programmatically with .net one way is to use a test tool like SOAPUI to produce the exact XML you think needs to be posted to the webservice and to send it manually with that tool

Then you can develop the .net equivalent

EDIT - here's a quick example I knocked up to call your example service (using SOAP1.2) based on the link above:

        {
            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://www.w3.org/2003/05/soap-envelope"">
  <soap:Body>
    <SayHello xmlns=""http://tempuri.org/"">
      <name>My Name Here</name>
    </SayHello>
  </soap:Body>
</soap:Envelope>";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:2439/Soap.asmx");
            req.ContentType = "application/soap+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();

            // Do whatever you need with the response
            Byte[] myData = ReadFully(responseStream);
            string s = System.Text.ASCIIEncoding.ASCII.GetString(myData);
        }

The ReadFully method comes from http://www.yoda.arachsys.com/csharp/readbinary.html and looks like it originated from Jon Skeet.

The code of the selected answer didn't worked for me. I had to add the SOAPAction in the header and also change the ContentType .

Here is the entire code:

var strRequest = @"<soap12:Envelope> 
                    ... 
                    </soap12:Envelope>";

string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);

request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";         
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");

byte[] data = Encoding.UTF8.GetBytes(strRequest);

request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();

return new HttpResponseMessage()
{
    Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

There is XML-RPC.NET which allows for creating bindings on-the-fly.

Eg (an example from their website):

[XmlRpcUrl("http://betty.userland.com/RPC2")]
public interface IStateName : IXmlRpcProxy
{
    [XmlRpcMethod("examples.getStateName")]
    string GetStateName(int stateNumber); 
}

If your service were really as simple as your example, then simply use "Add Service Reference" and use the proxy.

If that doesn't work, then use the command-line svcutil.exe program and post the error messages it prints.

Do not use WSDL.EXE unless you have no choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM