Calling an ASP.NET Web Service Method Using an HTTP Request

I want to call an ASP.NET web service via an HTTP POST request using C # (i.e. I don't want to use the SoapHttpClientProtocol object generated when wsdl.exe is run).

As far as I can tell, the process includes:

  • creating an HttpWebRequest object that points to the URL / method of the web service using the method;

  • Create xml xml envelope,

  • Serializing any parameters I want to pass to the web method using the XmlSerializer;

  • Executing the request and analyzing the response.

I would like to do this without copying and using the generated code.

(1) seems pretty straightforward;

(2) I don't know if the envelope is standard, or how it should change depending on the webservice method I am calling. I guess I might need to add custom soap headers if the service needs it?

(3) What is the process for this? I guess I need to do something like this:

MyClass myObj;
XmlSerializer ser = new XmlSerializer(myObj.GetType());
TextWriter writer = new StringWriter();
ser.Serialize(writer, myObj);
string soapXml = writer.ToString();
writer.Close();

      

Also, I think I should add soapXml to the soap: Body element

(4) I believe I should extract and deserialize the soap content: body element. Can we use the reverse side of the process in (3)?

Thank,

TO.

+2


source to share


1 answer


I don't know why I am doing this, but here is an example of manually invoking a web service. Please promise to never use this in production code.

Suppose you have the following SOAP service:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service1 : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld(Foo foo)
    {
        return "Hello World";
    }
}

      



You can call it manually like this:

class Program
{
    static void Main(string[] args)
    {
        using (WebClient client = new WebClient())
        {
            client.Headers.Add("SOAPAction", "\"http://tempuri.org/HelloWorld\"");
            client.Headers.Add("Content-Type", "text/xml; charset=utf-8");
            var payload = @"<?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><HelloWorld xmlns=""http://tempuri.org/""><foo><Id>1</Id><Name>Bar</Name></foo></HelloWorld></soap:Body></soap:Envelope>";
            var data = Encoding.UTF8.GetBytes(payload);
            var result = client.UploadData("http://localhost:1475/Service1.asmx", data);
            Console.WriteLine(Encoding.Default.GetString(result));
        }
    }
}

      

+7


source







All Articles