2014-02-18 103 views
0

我創建了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> 

我要去哪裏錯採取以下?

+0

你能舉一個你如何使用'WebClient'的例子嗎? – Tim

+0

我已更新我的問題 – Tommassiov

+0

如果您不拋出過錯,會發生什麼?故障意味着返回500錯誤,而不是400. –

回答

0

你有任何其他的網絡方法,你可以成功呼叫? (來自同一個非WCF客戶端)

由於你有一個400 http錯誤,在我看來,這個調用並不是以正確的方式構建或完成的,所以如果你可以在同一個服務中成功調用任何其他方法將幫助我們確保電話正確。

+0

如果我不引發FaultException,它會正常工作。 – Tommassiov

+0

所以這裏有2個鏈接可能會有所幫助:http://dotnet.dzone.com/news/wcf-rest-tip-2也是這樣的:http:// stackoverflow。com/questions/4461254/wcf-rest-services-generic-exception-handling – Jportelas

+0

我想爲Wcf RestFul服務獲取Xml或Json響應,是否可能 – Tommassiov