WCF如何全局处理错误

本文关键字:错误 处理 何全局 WCF | 更新日期: 2023-09-27 17:59:21

所以基本上我想集中处理WCF服务中的异常。为此,我创建了一个实现IErrorHandler的类和一个实现IServiceBehavior的类,在该服务行为实现中,我要说的是,对于每个通道调度程序,我都想像这样添加我的自定义错误处理程序。

public void ApplyDispatcherBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
    IErrorHandler errorHandler = new CustomErrorHandler();
    foreach (var channelDispatcher in serviceHostBase.ChannelDispatchers)
    {
        channelDispatcher.ErrorHandlers.Add(errorHandler);
    }
}

我所做的最后一件事是创建一个从具有适当实现的BehaviorExtensionElement派生的类,并在配置文件中注册扩展名。但它似乎不起作用。我的意思是,我想做的是,如果异常没有得到处理,我想在一个集中的地方处理它。但它似乎对我不起作用。我的实施正确吗?我是否误解了我实施的整个事情应该如何运作。任何建议都将不胜感激。

<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
    <bindings>
      <basicHttpBinding>
        <binding name="soapBinding" />
      </basicHttpBinding>
      <webHttpBinding>
        <binding name="webBinding" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="poxBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="defaultBehavior">
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="MyCustomBehaviorExtensionElement" type="MyNamespace.CustomExtensionElement, MyNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
      </behaviorExtensions>
    </extensions>
    <services>
      <service name="MyNamespace.MyService" behaviorConfiguration="defaultBehavior">
        <endpoint address="pox" binding="webHttpBinding" behaviorConfiguration="poxBehavior"
                  name="pox" contract="MyNamespace.IMyService" />
        <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="soapBinding"
                  name="soap" contract="MyNamespace.IMyService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Services" />
          </baseAddresses>
        </host>
      </service>

这是配置文件的一部分

WCF如何全局处理错误

在您的网络配置中错过

在您尚未应用扩展的情况下,您需要将您的扩展添加到您的服务行为中:

  <serviceBehaviors>
    <behavior name="defaultBehavior">
      <serviceDebug includeExceptionDetailInFaults="false" />
      <serviceMetadata httpGetEnabled="true" />
      <MyCustomBehaviorExtensionElement />
    </behavior>
  </serviceBehaviors>

WebHttpBinding:

但是,为了处理WebHttpBinding的错误,您必须使用这样的方法:

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using log4net;
namespace Server.Web
{
    public class WebHttpWithErrorHandlingElement : BehaviorExtensionElement
    {
        public class WebHttpWithErrorHandlingBehavior : WebHttpBehavior
        {
            internal sealed class WebHttpErrorHandler : IErrorHandler
            {
                private static readonly ILog logger = LogManager.GetLogger(typeof (WebHttpErrorHandler));
                public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
                {
                    var exception = new FaultException("Web Server error encountered. All details have been logged.");
                    var messageFault = exception.CreateMessageFault();
                    fault = Message.CreateMessage(version, messageFault, exception.Action);
                }
                public bool HandleError(Exception error)
                {
                    logger.Error(string.Format("An error has occurred in the Web service {0}", error));
                    return !(error is FaultException);
                }
            }
            protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                base.AddServerErrorHandlers(endpoint, endpointDispatcher);
                endpointDispatcher.DispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(new WebHttpErrorHandler());
            }
        }
        public WebHttpWithErrorHandlingElement()
        {
        }
        public override Type BehaviorType
        {
            get { return typeof (WebHttpWithErrorHandlingBehavior); }
        }
        protected override object CreateBehavior()
        {
            return new WebHttpWithErrorHandlingBehavior();
        }
    }
}

配置文件:

<system.serviceModel>
  <extensions>
    <behaviorExtensions>
      <add name="webHttpWhithErrorHanlding" type="Server.Web.WebHttpWithErrorHandlingElement, Server.Web"/>
    </behaviorExtensions>
  </extensions>

  <!-- other staff -->
  <behaviors>
    <endpointBehaviors>
      <behavior name="webBehavior">
        <webHttpWhithErrorHanlding />
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>

然后将其应用于您的端点:

  <service name="YourServiceContract">
    <endpoint address=""
              binding="webHttpBinding"
              behaviorConfiguration="webBehavior"
              contract="IYourServiceContract"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost/"/>
      </baseAddresses>
    </host>        
  </service>