2011-11-07 26 views
2

首先稍微介紹一下背景:我在WCF 4中有一個使用WebHttpEndpoint的REST服務。我沒有在每個服務方法或每個服務類中都有顯式的錯誤處理程序,而是希望有一個集中的錯誤處理來記錄日誌,並且能夠包裝一個很好的自定義消息以傳遞給客戶端。無法添加自定義WebHttpBehavior:無法使用相同的鍵添加兩個項目

我試圖通過實現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" />  

如果整個方法錯誤處理似乎是一個壞主意,隨時發表評論...

但是,我的問題是爲什麼我得到這個異常時,服務三ES開始:

[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或行爲可以單獨存在,但他們不會共存。

回答

2

您的<errorHandler>已經是-a WebHttpBehavior(這是與<webHttp/>配置元素相關的行爲)。您應更新與<errorHandler>關聯的行爲擴展,以瞭解要傳遞給WebHttpBehavior的參數,並且只有該參數。

+0

是的,這是有道理的。謝謝! :) – kodbuse

+0

不明白你在說什麼 – PositiveGuy