如果我从 中派生所有异常WebFaultException
,并直接从我的服务中抛出它们,则设置中的 StatusCode 将WebFaultException
传递给客户端。我宁愿不必这样做,因为我宁愿NotImplementedException
从我的代码中抛出像 , 这样的通用异常。
我已经设置了一个 IErrorHandler,期望我能够捕获像这样NotImplementedException
的异常,然后只转换到WebFaultException
那里。
我的代码如下所示:
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>
- 为什么没有返回正确的状态码?
- 为什么json中没有body?
补充:我已经尝试过将 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());