我创建了一个 Wcf 服务。Wcf 客户端和非 Wcf 客户端都可以访问它。我为 FaultException 处理创建了自己的类,如下所示;
[DataContract]
public class ErrorResponse
{
[DataMember]
public string ErrMsg {get;set;}
}
对于我的服务接口,我有
[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContract (typeof(ErrorResponse))]
[WebInvoke(Method = "POST", UriTemplate = "/XML/GetTypes", BodyStyle = WebMessageBodyStyle.Bare)]
TypeResponse XMLTypes(TypeRequest TypeRequest);
}
在我的方法 XmlTypes 中,我有以下内容;
public static TypeResponse XmlTypes(TypeRequest TypeRequest)
{
//do something
//raise a error
ErrorResponse oErrorResponse = new ErrorResponse();
oErrorResponse.ErrMsg = "Some Error happened";
FaultCode oFaultCode = new FaultCode("12345");
throw new FaultException<ErrorResponse>(oErrorResponse , new FaultReason ("Reason for the fault"),
new FaultCode("TypeRequestFailed", new FaultCode("TypeNotFound")));
这似乎适用于 Wcf 客户端。
但是,当从非 Wcf 客户端进行调用时,例如使用 WebClient UploadString(我知道我可以使用服务参考,这是出于测试目的),我回来了
System.Net.WebException:远程服务器返回错误:(400)错误请求。
这是我在另一个测试应用程序中的网络客户端代码;
WebClient oClient = new WebClient();
oClient.Encoding = UTF8Encoding.UTF8;
oClient.Headers.Add("Content-Type", "application/xml");
try
{
txtResponse.Clear();
sRequest = "<TypeRequest><UserId>1</UserId><Password>asdax12</Password></TypeRequest>";
txtResponse.Text = oClient.UploadString("http://localhost:49562/Service.svc/XML/XmlTypes", "POST", sRequest).ToString();
}
catch (Exception ex)
{
txtResponse.Text = ex.ToString();
}
在我的 webconfig 文件中,我添加了以下内容,取自 this example throwing soap faults for non wcf clients
<system.serviceModel>
<bindings>
<customBinding>
<binding name="basicHttpSoap12Binding">
<textMessageEncoding messageVersion="Soap12"/>
<httpTransport/>
</binding>
</customBinding>
</bindings>
<services>
<service name="MySoap12Service">
<endpoint address="" binding="customBinding" bindingConfiguration="basicHttpSoap12Binding"
bindingNamespace="MySoap12ServiceNamespace"
contract="MySoap12Service">
</endpoint>
</service>
</services>
</system.serviceModel>
我哪里错了?