如果我从WebFaultException
派生所有异常,并直接从我的服务中抛出它们,则WebFaultException
中设置的StatusCode会传递给客户端。我宁愿不必这样做,因为我宁愿从我的代码中抛出NotImplementedException
之类的通用异常。
我已经设置了一个IErrorHandler,期望我能够捕获NotImplementedException
之类的异常,然后转换到那里的WebFaultException
。 / p>
我的代码如下所示:
public class HTTPBindingErrorHandler: IErrorHandler
{
public void ProvideFault(Exception exception, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
if (exception is NotImplementedException)
{
WebFaultException wfe = new WebFaultException(HttpStatusCode.NotImplemented);
MessageFault mf = wfe.CreateMessageFault();
fault = Message.CreateMessage(version, mf, wfe.Action);
}
}
public bool HandleError(Exception exception)
{
return false;
}
}
当单步执行时,我看到我正在使用ProvideFault中的代码,但返回给客户端的状态是400,而不是501.此外,正文是:
<Fault
xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">
<Code>
<Value>Receiver</Value>
<Subcode>
<Value
xmlns:a="http://schemas.microsoft.com/2009/WebFault">a:NotImplemented
</Value>
</Subcode>
</Code>
<Reason>
<Text xml:lang="en-US">Not Implemented</Text>
</Reason>
</Fault>
增加: 我已经尝试过将AutomaticFormatSelectionEnabled = false设置为webhttpbehavior的建议,但它仍然不起作用。我自我托管,但我认为这不应该有所作为。这是我用来设置服务的代码:
Uri newUri = new Uri(info.baseURI, info.Path);
WebServiceHost host = new WebServiceHost(info.Type, newUri);
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.InheritedFromHost;
ServiceEndpoint ep = host.AddServiceEndpoint(info.Interface, binding, newUri);
ep.Behaviors.Add(new WebHttpBehavior() {
DefaultOutgoingResponseFormat = WebMessageFormat.Json,
DefaultBodyStyle = WebMessageBodyStyle.Wrapped,
AutomaticFormatSelectionEnabled = false } );
ep.Behaviors.Add(new WebHttpCors.CorsSupportBehavior());
ep.Behaviors.Add(new HTTPBindingErrorBehavior());