2011-05-16 109 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