【发布时间】:2017-08-20 00:26:22
【问题描述】:
我目前有 2 个应用程序:
- WCF 服务
- 向我的 WCF 服务触发 HTTP 请求的控制台应用程序
我想向我的 WCF 服务发送 SOAP 消息并解析从 WCF 服务返回的 XML 数据。我可以使用纯 XML 和此端点 URL http://localhost:62147/Service1.svc/Http/ 成功 GET 和 POST,但使用 SOAP 则无法正常工作。发送请求时出现以下错误。
例外
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (400) Bad Request.
WCF 服务 web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfService1.Service1">
<endpoint address="Soap" binding="basicHttpBinding" contract="WcfService1.IService1" />
<endpoint address="Http" kind="webHttpEndpoint" contract="WcfService1.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpErrors errorMode="Detailed"/>
</system.webServer>
</configuration>
WCF IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke]
string GetData(string channel);
}
控制台应用
private static string HttpPost(string _postData)
{
using (WebClient webClient = new WebClient())
{
webClient.BaseAddress = "http://localhost:62147/Service1.svc/Soap/";
webClient.Headers.Add("Content-Type", "text/xml; charset=utf-8");
webClient.Headers.Add("SOAPAction", "http://tempuri.org/IService1/GetData");
byte[] response = webClient.UploadData("GetData", Encoding.UTF8.GetBytes(_postData));
return Encoding.UTF8.GetString(response);
}
}
肥皂消息 我从 WCF 测试客户端复制了这个。
const string soapMsg = @"
<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Header>
<Action s:mustUnderstand=""1"" xmlns=""http://schemas.microsoft.com/ws/2005/05/addressing/none"">http://tempuri.org/IService1/GetData</Action>
</s:Header>
<s:Body>
<GetData xmlns=""http://tempuri.org/"">
<channel>1</channel>
</GetData>
</s:Body>
</s:Envelope>";
【问题讨论】:
-
尝试
<endpoint address="Soap" binding="wsHttpBinding" contract="WcfService1.IService1" />而不是<endpoint address="Soap" binding="basicHttpBinding" contract="WcfService1.IService1" />。 BasicHttpBinding 是旧绑定,如果可用,请使用 wsHttpBinding -
@tomassino 同样的错误。