How to post SOAP Request from .NET? How to post SOAP Request from .NET? xml xml

How to post SOAP Request from .NET?


var uri = new Uri("http://localhost/SOAP/SOAPSMS.asmx/add");var req = (HttpWebRequest) WebRequest.CreateDefault(uri); req.ContentType = "text/xml; charset=utf-8"; req.Method = "POST"; req.Accept = "text/xml"; req.Headers.Add("SOAPAction", "http://localhost/SOAP/SOAPSMS.asmx/add"); var strSoapMessage = @"<?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><add xmlns='http://tempuri.org/'><a>23</a><b>5</b></soap:Body></soap:Envelope>"; using (var stream = new StreamWriter(req.GetRequestStream(), Encoding.UTF8))     stream.Write(strSoapMessage); 


I've done something like this, building an xml request manually and then using the webrequest object to submit the request:

string data = "the xml document to submit";string url = "the webservice url";string response = "the response from the server";// build request objects to pass the data/xml to the serverbyte[] buffer = Encoding.ASCII.GetBytes(data);HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.ContentLength = buffer.Length;Stream post = request.GetRequestStream();// post data and close connectionpost.Write(buffer, 0, buffer.Length);post.Close();// build response objectHttpWebResponse response = request.GetResponse() as HttpWebResponse;Stream responsedata = response.GetResponseStream();StreamReader responsereader = new StreamReader(responsedata);response = responsereader.ReadToEnd();

The string variables at the start of the code are what you set, then you get a string response (hopefully...) from the server.


This isn't the normal way. Usually you would use WCF or the older style web service reference to generate a proxy client for you.

However, what you need to do generally is use HttpWebRequest to connect to the URL and then send the XML in the body of the request.