首先一点背景知识:我在 WCF 4 中有一个使用 WebHttpEndpoint 的 REST 服务。我不想在每个服务方法甚至每个服务类中都有明确的错误处理程序,而是希望有一个集中的错误处理程序,它可以进行日志记录并能够包装一个很好的自定义消息以传递给客户端。
我试图通过实现 IErrorHandler 并使用客户 WebHttpBehavior 添加它来做到这一点:
public class ErrorHandlerBehavior : WebHttpBehavior
{
protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
base.AddServerErrorHandlers(endpoint, endpointDispatcher);
}
}
然后我使用 ExtensionElement 添加它:
<behaviors>
<endpointBehaviors>
<behavior>
<authenticationInspector />
<authorizationInspector />
<errorHandler />
<webHttp
defaultBodyStyle="Bare"
defaultOutgoingResponseFormat="Json"
helpEnabled="true" />
如果整个错误处理方法看起来是个坏主意,请随时对此发表评论......
但是,我的问题是为什么在服务尝试启动时会出现此异常:
[ArgumentException: Cannot add two items with the same key to SynchronizedKeyedCollection.]
System.Collections.Generic.SynchronizedKeyedCollection`2.AddKey(K key, T item) +12277986
System.Collections.Generic.SynchronizedKeyedCollection`2.InsertItem(Int32 index, T item) +38
System.ServiceModel.Dispatcher.OperationCollection.InsertItem(Int32 index, DispatchOperation item) +53
System.Collections.Generic.SynchronizedCollection`1.Add(T item) +78
System.ServiceModel.Description.WebHttpBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) +2498
System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost) +4275
System.ServiceModel.ServiceHostBase.InitializeRuntime() +60
System.ServiceModel.ServiceHostBase.OnBeginOpen() +27
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +50
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +318
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +206
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +651
[ServiceActivationException: The service '/api/Errors' cannot be activated due to an exception during compilation. The exception message is: Cannot add two items with the same key to SynchronizedKeyedCollection..]
System.Runtime.AsyncResult.End(IAsyncResult result) +688590
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +190
System.ServiceModel.Activation.AspNetRouteServiceHttpHandler.EndProcessRequest(IAsyncResult result) +6
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +96
看起来 webHttp 或 errorHandler 行为都可以单独存在,但它们不会共存。