1

我有简单的 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 消息返回给调用客户端?IE:

<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>
4

2 回答 2

2

我认为您需要在操作上声明一个 FaultContract 并使用 FaultException(SoapException 是 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());
    }
}
于 2011-05-16T13:34:31.753 回答
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>
于 2011-05-16T13:46:19.837 回答