Question : How do you create a manual SOAP request to a web service in C#?

I created a sample Console application that calls the TempConvert web service to convert temperatures between Fahrenheit and Celsius.  The web service takes a temperature value and converts it and returns the converted value.

When I call the web service, I get the following error;
“The remote server returned an error: (400) Bad Request at System.Net.HttpWebRequest.GetResponse()”

I am not sure why I get this error.  Any suggestions?  Thank you in an advance for a timely response.

Please Note
I created this sample application to illustrate what I am attempting to accomplish in my other application.  Using the WSDL to create the web method stubs is not an option because my application will not know the web service locations until it is deployed.  So, please do not suggest that I use wsdl.exe to generate the web method stubs.

TempConvert web service URI
http://www.w3schools.com/webservices/tempconvert.asmx
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebServiceCallConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string selection;
            string valueToBeConverted;
            string convertedValue;

            Console.Title = "Temperature Conversion";

            Console.WriteLine("Select Conversion");
            Console.WriteLine("-----------------");
            Console.WriteLine("1) Fahrenheit to Celsius");
            Console.WriteLine("2) Celsius to Fahrenheit\n");
            selection = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Enter Value to Convert");
            Console.WriteLine("----------------------");
            valueToBeConverted = Console.ReadLine();
            Console.WriteLine("");

            convertedValue = ConvertValue(Int32.Parse(selection), valueToBeConverted);

            Console.WriteLine("Conversion Result");
            Console.WriteLine("-----------------");
            Console.WriteLine(convertedValue);

            // Exit application
            Console.WriteLine("");
            Console.WriteLine("Press any key to exit!");
            Console.ReadLine();
        }

        private static string ConvertValue(int selection, string valueToBeConverted)
        {
            string value;
            string uriString;
            string returnValue;
            string soapAction = "";
            string displayText = "";

            uriString = "http://www.w3schools.com/webservices/tempconvert.asmx";

            switch (selection)
            {
                case 1: // Convert Fahrenheit to Celsius
                    soapAction = "http://tempuri.org/FahrenheitToCelsius";
                    displayText = " Celsius";
                    break;

                case 2: // Convert Celsius to Fahrenheit
                    soapAction = "http://tempuri.org/CelsiusToFahrenheit";
                    displayText = " Fahrenheit";
                    break;
            }

            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(uriString));
                httpRequest.Method = "POST";
                httpRequest.ContentType = "text/xml; charset=utf-8";
                httpRequest.Headers.Add(String.Format("SOAPAction: \"{0}\"", soapAction));

                byte[] bytes = Encoding.UTF8.GetBytes(valueToBeConverted);
                httpRequest.ContentLength = valueToBeConverted.Length;

                httpRequest.ReadWriteTimeout = 10;
                httpRequest.ProtocolVersion = HttpVersion.Version11;

                using (Stream requestStream = httpRequest.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader responseStreamReader = new StreamReader(responseStream);
                    value = responseStreamReader.ReadToEnd();
                }

                returnValue = value + displayText;
            }
            catch (Exception ex)
            {
                returnValue = "Error : " + ex.ToString();
            }

            return returnValue;
        }
    }
}

Answer : How do you create a manual SOAP request to a web service in C#?

I got this to work for me for the Celsius to Fahrenheit (error with option 1):

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace WebServiceCallConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string selection;
            string valueToBeConverted;
            string convertedValue;

            Console.Title = "Temperature Conversion";

            Console.WriteLine("Select Conversion");
            Console.WriteLine("-----------------");
            Console.WriteLine("1) Fahrenheit to Celsius");
            Console.WriteLine("2) Celsius to Fahrenheit\n");
            selection = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Enter Value to Convert");
            Console.WriteLine("----------------------");
            valueToBeConverted = Console.ReadLine();
            Console.WriteLine("");

            convertedValue = ConvertValue(Int32.Parse(selection), valueToBeConverted);

            Console.WriteLine("Conversion Result");
            Console.WriteLine("-----------------");
            Console.WriteLine(convertedValue);

            // Exit application
            Console.WriteLine("");
            Console.WriteLine("Press any key to exit!");
            Console.ReadLine();
        }

        private static string ConvertValue(int selection, string valueToBeConverted)
        {
            string value;
            string uriString;
            string returnValue;
            string soapAction = "";
            string displayText = "";
            string resultName = "";

            uriString = "http://www.w3schools.com/webservices/tempconvert.asmx";

            switch (selection)
            {
                case 1: // Convert Fahrenheit to Celsius
                    soapAction = "http://tempuri.org/FahrenheitToCelsius";
                    displayText = " Celsius";
                    resultName = "FahrenheitToCelsiusResult";
                    break;

                case 2: // Convert Celsius to Fahrenheit
                    soapAction = "http://tempuri.org/CelsiusToFahrenheit";
                    displayText = " Fahrenheit";
                    resultName = "CelsiusToFahrenheitResult";
                    break;
            }

            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(new Uri(uriString));
                httpRequest.Method = "POST";
                httpRequest.ContentType = "text/xml; charset=utf-8";
                httpRequest.Headers.Add(String.Format("SOAPAction: \"{0}\"", soapAction));

                Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.SoapAction.xml");

                using (StreamReader reader = new StreamReader(stream))
                {
                    string soapActionXml = reader.ReadToEnd().Replace("string", valueToBeConverted);

                    byte[] buffer = Encoding.UTF8.GetBytes(soapActionXml);
                    httpRequest.ContentLength = buffer.Length;

                    httpRequest.ReadWriteTimeout = 10;
                    httpRequest.ProtocolVersion = HttpVersion.Version11;

                    Stream requestStream = httpRequest.GetRequestStream();
                    requestStream.Write(buffer, 0, buffer.Length);

                    HttpWebResponse response = (HttpWebResponse) httpRequest.GetResponse();

                    Stream responseStream = response.GetResponseStream();
                    StreamReader responseStreamReader = new StreamReader(responseStream);
                    value = responseStreamReader.ReadToEnd();

                    XDocument document = XDocument.Parse(value);

                    string elementName = "{http://tempuri.org/}" + resultName;
                    returnValue = document.Descendants(elementName).FirstOrDefault().Value;
                }
            }
            catch (Exception ex)
            {
                returnValue = "Error : " + ex.ToString();
            }

            return returnValue;
        }
    }
}
Random Solutions  
 
programming4us programming4us