Using ASMX webservices with HttpWebRequest in c# 4.0

If you want to call a .NET 4.0 C# web service, without using the WSDL or “Add Service Reference” in Microsoft Visual Studio 2015, you can use the following functions written in c#:

/// <summary>
/// Execute a Soap WebService call
/// </summary>
public override void Execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?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>
<HelloWorld3 xmlns=""http://tempuri.org/"">
<parameter1>test</parameter1>
<parameter2>23</parameter2>
<parameter3>test</parameter3>
</HelloWorld3>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream()) 
{ 
soapEnvelopeXml.Save(stream); 
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream())) 
{ 
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
} 
}
}
/// <summary>
/// Create a soap webrequest to [Url]
/// </summary>
/// <returns></returns>
public HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://dev.nl/Rvl.Demo.TestWcfServiceApplication/SoapWebService.asmx"); 
webRequest.Headers.Add(@"SOAP:Action"); 
webRequest.ContentType = "text/xml;charset=\"utf-8\""; 
webRequest.Accept = "text/xml"; 
webRequest.Method = "POST"; 
return webRequest; 
}

Result

<?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><HelloWorld3Response xmlns=”http://tempuri.org/”><HelloWorld3Result>test</HelloWorld3Result></HelloWorld3Response></soap:Body></soap:Envelope>

 

You can use complex types in you’re request. I use fiddler to get the contents of the soap envelope.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s