.NET SOAP请求返回“400 Bad Request”

时间:2014-10-23 15:06:04

标签: c# soap httprequest

我正在尝试为Web服务创建一个简单的XML SOAP请求。

服务本身被证明是可以的,我通过使用WSDL生成的类来访问它而没有任何问题。但是,如果我尝试使用常规WebRequest访问它 - 它总是返回400 Bad Request。

这是我的代码:

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;
    }
}

XML由SoapUI生成并在那里完美地运行。这是SoapUI的HTTP标头:

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)

我做错了什么?

UPD:将服务从我改为第三方: http://wsf.cdyne.com/WeatherWS/Weather.asmx 通过WSDL - 它的工作原理。 SoapUI返回数据。从我的代码 - 内部错误500。

1 个答案:

答案 0 :(得分:0)

尝试从肥皂信息中删除回车 .Replace("\r\n", ""); 如果不行,请验证用fiddler发出的http请求,对我来说非常有用。