简体   繁体   中英

.NET SOAP request returns “400 Bad Request”

I am trying to create a simple XML SOAP request to a web service.

The service itself is proven to be OK, I accessed it by using WSDL-generated class without any problems. But if I try to access it using regular WebRequest - it always returns 400 Bad Request.

Here's my code:

class Program
{

    static void Main(string[] args)
    {

        HttpWebRequest request = CreateWebRequest("http://localhost:8000/ExchangeService", "WhoAmI");
        XmlDocument SoapEnvelopeXml = new XmlDocument();
        SoapEnvelopeXml.LoadXml(
        @"<?xml version=""1.0""?>
        <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope"" 
        xmlns:tem=""http://tempuri.org"">
        <soapenv:Header/>
        <soapenv:Body>
        <tem:WhoAmI/></soapenv:Body></soapenv: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);
            }
        }

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    public static HttpWebRequest CreateWebRequest(string url, string soapAction)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.ContentType = "text/xml;charset=UTF-8;action=\"" + soapAction + "\"";
        webRequest.Method = "POST";
        return webRequest;
    }
}

The XML is generated by SoapUI and works there perfectly. Here is the SoapUI's HTTP header:

POST http://localhost:8000/ExchangeService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://tempuri.org/IExchangeFunctions/WhoAmI"
Content-Length: 211
Host: localhost:8000
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

What am I doing wrong?

UPD: changed the service from my to some third-party: http://wsf.cdyne.com/WeatherWS/Weather.asmx Through WSDL - it works. SoapUI returns data. From my code - Internal Error 500.

Try remove carriage return from soap message .Replace("\\r\\n", ""); If not work verify the http request sended with fiddler, to me it was very helpful.

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