使用C#通过WebRequest调用WCF服务获取400个错误请求

时间:2011-03-29 16:12:14

标签: wcf soap httpwebrequest webrequest

在对代码进行一些更改并经历链接之后,我能够编写以下代码来使用SOAP消息调用WCF服务方法。现在我得到400 Bad Request错误,无论我改变什么(试过HttpWebRequest)我仍然得到这个错误。不确定我错过了什么:

private string WebServiceCall()
{
    WebRequest req = WebRequest.Create("http://klo239fu.mass.win.tf.com/WCFTestService/Service.svc");
    req.ContentType = "application/soap+xml; charset=utf-8";
    req.Method = "POST";
    req.Headers.Add("SOAPAction", "http://tempuri.org/GetSimpleType");
    using(Stream reqStream = req.GetRequestStream())
    {
        var bytes = Encoding.UTF8.GetBytes(txtFormattedSoap.Text);
        reqStream.Write(bytes, 0, bytes.Length);
        reqStream.Close();
    }
    var wr = (WebRespose)req.GetResponse();
    var srd = new StreamReader(wr.GetResponseStream());
    txtResponse.Text = srd.ReadToEnd();
}

SOAP请求(来自SOAP客户端)

POST /WCFTestService/Service.svc HTTP/1.1
Host: klo239fu.mass.win.tf.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "wsf-test-service/IService/GetSimpleType"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
 <soap:Body>
 <GetSimpleType xmlns="wsf-test-service">
  <myvalue>int</myvalue>
 </GetSimpleType>
 </soap:Body>
</soap:Envelope>

这是我在代码中传递给上面的soap enveope的SOAP请求:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetSimpleType xmlns="wcf-test-service"><myvalue>1234</myvalue></GetSimpleType></soap:Body></soap:Envelope>

之前我有内容类型test / xml但代码抛出“(415)无法处理消息,因为内容类型'text / xml'不是预期的类型。”所以我更改了内容类型=“application / soap + xml; charset = utf-8”,但它失败了(400)错误的请求。

1 个答案:

答案 0 :(得分:2)

我看到你发布的帖子,我认为你和我目前正在做同样的事情。动态调用Web服务。加载WSDL,使用动态代理和反射以及所有有趣的东西。

我建议你看到这个错误。 我使用过的一个Web服务遇到了类似的问题。即使标题中的Action被认为是可选的,当我传递地址(uri)时,它确实设法让我的调用失败。当我传入操作的名称而不是它工作。所以试着改变这个:

req.Headers.Add("SOAPAction", "http://tempuri.org/GetSimpleType"); 

改为使用WSDL中的方法名称。这是System.ServiceModel.Description.OperationDescription的名称。它可能是“GetSimpleType”。

req.Headers.Add("SOAPAction", "GetSimpleType"); 
相关问题