2011-05-16 108 views
1

我已經asimple WCF HTTP/SOAP的Web服務,該服務實現看起來是這樣的:現在WCF HTTP/SOAP web服務 - 在故障返回異常消息

public CustomResponse DoSomething(CustomRequest request) 
{ 
    try 
    { 
     return InternalGubbins.WithErrorHandling.ProcessRequest(request); 
    } 
    catch 
    { 
     // Some sort of error occurred that is not gracefully 
     // handled elsewhere in the framework 
     throw new SoapException("Hmmm, it would seem that the cogs are meshed!", SoapException.ServerFaultCode); 
    } 
} 

,如果的SoapException拋出我想異常消息(即Hmmm, it would seem that the cogs are meshed!)將被返回給調用客戶端,而不需要任何額外的異常細節(即堆棧跟蹤)。

如果我將includeExceptionDetailInFaults設置爲true(服務器上的web.config),則帶有堆棧跟蹤等的完整異常將返回給客戶端。但是,如果我將它設置爲false,我得到一個通用的消息:

服務器無法處理請求 由於內部錯誤。有關錯誤 的更多信息, 上 IncludeExceptionDetailInFaults(無論是從ServiceBehaviorAttribute 或從 配置 行爲),以便在服務器上 或者反過來發送異常信息回 客戶端,或打開跟蹤按 Microsoft .NET Framework 3.0 SDK 文檔和檢查服務器 跟蹤日誌。

所以問題是,我怎樣才能讓我的SoapException消息返回到調用客戶端?即:

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"> 
    <s:Header> 
     <a:Action s:mustUnderstand="1">http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault</a:Action> 
     <a:RelatesTo>urn:uuid:185719f4-6113-4126-b956-7290be375342</a:RelatesTo> 
    </s:Header> 
    <s:Body> 
     <s:Fault> 
      <s:Code> 
       <s:Value>s:Receiver</s:Value> 
       <s:Subcode> 
        <s:Value xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</s:Value> 
       </s:Subcode> 
      </s:Code> 
      <s:Reason> 
       <s:Text xml:lang="en-GB">Hmmm, it would seem that the cogs are meshed!</s:Text> 
      </s:Reason> 
     </s:Fault> 
    </s:Body> 
</s:Envelope> 

回答

2

我認爲你需要聲明一個FaultContract的操作和使用FaultException(SoapException是前WCF)。我相信如果WCF不屬於服務合同的一部分,WCF不會將故障發回客戶端。我從來沒有嘗試SoapException,但肯定拋出一個FaultException對我來說一直工作正常。

[ServiceContract()]  
public interface ISomeService 
{ 
    [OperationContract] 
    [FaultContract(typeof(MyFault))] 
    CustomResponse DoSomething(CustomRequest request) 
} 

public class SomeService 
{ 
    public CustomResponse DoSomething(CustomRequest request) 
    { 
     ... 
     throw new FaultException<MyFault>(new MyFault()); 
    } 
} 
+0

這工作完全和也回答下一個在肥皂異常中使用自定義細節的問題。乾杯 – MrEyes 2011-05-16 17:28:40

1

如果你不希望定義一個自定義異常類型,那麼試試這個

try  
{   
    return InternalGubbins.WithErrorHandling.ProcessRequest(request);  
}  
catch  
{ 
    throw new FaultException("Hmmm, it would seem that the cogs are meshed.");  
} 

這樣做會發送以下響應客戶端

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Header /> 
    <s:Body> 
    <s:Fault> 
     <faultcode>s:Client</faultcode> 
     <faultstring xml:lang="en-US">Hmmm, it would seem that the cogs are meshed.</faultstring> 
    </s:Fault> 
    </s:Body> 
</s:Envelope> 
+0

這似乎很好地工作,但是...我正在使用Microsoft服務跟蹤查看器來查看服務請求的痕跡。出於某種原因使用FaultException時,跟蹤查看器不起作用。 – MrEyes 2011-05-16 16:19:54