无法添加自定义WebHttpBehavior:无法使用相同的键添加两个项目

时间:2011-11-07 21:53:15

标签: .net wcf wcf-binding webhttpbinding wcf-behaviour

首先介绍一下:我在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行为本身可以存在,但它们不会共存。

1 个答案:

答案 0 :(得分:2)

您的<errorHandler>已经是WebHttpBehavior(这是与<webHttp/>配置元素相关联的行为)。您应该更新与<errorHandler>关联的行为扩展,以了解要传递给WebHttpBehavior的参数,并且只有那个参数。