2016-06-13 71 views
0

提供了故障狀態我有一個WCF服務,我打電話方式如下:爲WCF服務

MyService client = new MyService(); 
bool result = client.MyServiceMethod(param1, param2); 

可變結果設置爲true或false指示成功或失敗。在成功的情況下,這是明確的,但在失敗的情況下,我需要得到一些失敗的細節。

從我的服務,我用

OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; 
response.StatusCode = HttpStatusCode.BadRequest; 
response.StatusDescription = "Invalid parameter."; 
return false; 

我的問題是我如何檢索響應描述是正確的方式來提供故障反饋?

回答

0

IMO最好是定義一個自定義類,你再從返回你的方法。這個類將包含任何錯誤的細節。你使用DataContracts來做到這一點。

一個簡單的例子可能是這樣的......

[ServiceContract] 
public interface IMyContract 
{ 
    [OperationContract] 
    MyResult DoSomething(); 
} 

[DataContract] 
public class MyResult 
{ 
    [DataMember] 
    public bool IsSuccess { get; set; } 

    [DataMember] 
    public string ErrorDetails { get; set; } 
} 


public class MyService : IMyContract 
{ 
    public MyResult DoSomething() 
    { 
     try 
     { 
      return new MyResult { IsSuccess = true }; 
     } 
     catch 
     { 
      return new MyResult { IsSuccess = false, ErrorDetails = "Bad things" }; 
     } 
    } 
} 

編輯:包括耗時根據註釋代碼。

var client = new MyService(); 
var results = client.DoSomething(); 

if (results.IsSuccess) 
{ 
    Console.WriteLine("It worked"); 
} 
else 
{ 
    Console.WriteLine($"Oops: {results.ErrorDetails}"); 
} 
+0

我該如何從調用程序中檢索細節? 對象結果= client.MyServiveMethod(param1,param2);將不起作用 – ElenaDBA

+0

爲發佈添加了詳細信息。如果您有任何問題,請告訴我。 –

0

通常您使用SOAP MSDN:Faults向客戶端傳達問題。故障的特殊優勢是WCF將確保您的通道在收到故障消息後保持打開狀態。默認情況下,該服務不會發送任何解釋發生的信息。 WCF不會透露有關該服務在內部執行的操作的詳細信息。有關更多詳細信息,請參閱MSDN:Specifying and Handling Faults in Contracts and Services。另請參閱SO:What exception type should be thrown with a WCF Service?

出於調試的目的,您可以添加ServiceDebug行爲,並設置IncludeExceptionDetailInFaults爲true,以獲取堆棧跟蹤(在非生產環境)