我創建了Wcf服務。它將由Wcf客戶端和非Wcf客戶端訪問。我爲FaultException處理創建了我自己的類,如下所示;處理非WCF客戶端的WCF故障
[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客戶端來說,這似乎工作正常。
但是,使用Web客戶端UploadString(我知道我可以使用服務引用,這是用於測試目的)使得從非WCF客戶的電話時,例如,我回來
System.Net.WebException: The remote server returned an error: (400) Bad Request.
這是我的另一個測試應用程序中的webclient代碼;
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文件我加入從這個例子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>
我要去哪裏錯採取以下?
你能舉一個你如何使用'WebClient'的例子嗎? – Tim
我已更新我的問題 – Tommassiov
如果您不拋出過錯,會發生什麼?故障意味着返回500錯誤,而不是400. –