wcf - IErrorHandler 未被绑定(bind),且未处理错误

标签 wcf error-handling ierrorhandler

我有一个 WCF 服务,我有一个绑定(bind)了 IErrorHandler 的 FaultContract,它运行良好。出于某种我不知道的原因,它在运行时停止绑定(bind)。当我在 ApplyDispatchBehaviorValidate 上放置断点时,当我开始调试时它们没有被调用(它用来停止),所以当我得到时我的异常没有被处理一个错误。
我最初关注 this blog post实现它,它工作正常,但是当我添加第二个接口(interface)/端点时,它停止工作。我根据 this SO post 更改了所有代码,但无济于事。开始发生的另一件事是,当我使用 Microsoft 服务配置编辑器打开 web.config 时,出现错误:

The 'TestAppServer, Version 1.0.0.0, Culture=neutral, PublicKeyToken=null' assembly could not be found. Do you want to locate it? If you select 'No', you will not be prompted for the same assembly again. To avoid seeing this message every time the system cannot fund the assembly, please copy the assembly file to the same folder as the configuration file.

在我添加第二个端点/接口(interface)后,当我在我的 WCF 服务上丢失错误处理时,上面的错误开始发生。下面是我的网络配置:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="ServiceErrorHandler" type="company.Test.appserver.implementation.ServiceErrorHandlerBehaviorExtensionElement, TestAppServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
    <bindings>
      <basicHttpBinding>
        <binding name="SimpleBinding" />
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="DefaultBehavior" name="company.Test.appserver.implementation.TestUpdate">
        <endpoint address="udt" binding="basicHttpBinding" bindingConfiguration="SimpleBinding"
          name="TestUpdate" bindingNamespace="http://company/Test/update/2011/04"
          contract="company.Test.appserver.interfaces.ITestUpdate" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
          name="TestUpdateMex" bindingNamespace="http://company/Test/update/2011/04"
          contract="IMetadataExchange" />
      </service>
      <service behaviorConfiguration="DefaultBehavior" name="company.Test.appserver.implementation.TestTransaction">
        <endpoint address="udt" binding="basicHttpBinding" bindingConfiguration="SimpleBinding"
          name="TestTransacao" bindingNamespace="http://company/Test/transaction/2011/04"
          contract="company.Test.appserver.interfaces.ITestTransacao" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
          name="TestTransacaoMex" bindingNamespace="http://company/Test/transaction/2011/04"
          contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetBinding="webHttpBinding"
            httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpGetBinding="webHttpBinding"
            httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

下面是我的错误处理程序的代码:

namespace company.Test.appserver.implementation
{
  public class ServiceErrorHandlerBehaviorExtensionElement : BehaviorExtensionElement, IServiceBehavior
  {
    public override Type BehaviorType
    {
      get { return typeof(TestErrorHandler); }
    }

    protected override object CreateBehavior()
    {
      return new TestErrorHandler();
    }

    private IErrorHandler GetInstance()
    {
      return new TestErrorHandler();
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
      IErrorHandler errorHandlerInstance = GetInstance();
      foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
      {
        ChannelDispatcher cd = cdb as ChannelDispatcher;

        if (cd != null)
        {
          cd.ErrorHandlers.Add(errorHandlerInstance);
        }
      }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
      foreach (var svcEndpoint in serviceDescription.Endpoints)
      {
        if (svcEndpoint.Contract.Name != "IMetadataExchange")
        {
          foreach (var opDesc in svcEndpoint.Contract.Operations)
          {
            if (opDesc.Faults.Count == 0)
            {
              string msg = string.Format("");
            }
          }
        }
      }
    }
  }

  public class TestErrorHandler : IErrorHandler
  {
    public bool HandleError(Exception error)
    {
      return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
      if (!(error is FaultException))
      {
        ClsTestFaultContract exContract = new ClsTestFaultContract();

        FaultException<ClsTestFaultContract> fex = 
          new FaultException<ClsTestFaultContract>(exContract, exContract.DescricaoErro,
            new FaultCode(Convert.ToString(exContract.CodigoErro)));
        MessageFault msgFault = fex.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, ErrorHandlerConstant.FaultAction); 
      }
    }
  }
}

下面是我的界面之一:

namespace company.Test.appserver.interfaces
{
  [ServiceContract(Namespace = "http://company/Test/transaction/2011/04",
            Name = "ITestTransacao", SessionMode = SessionMode.Allowed)]
  public interface ITestTransacao
  {
    [OperationContract]
    [FaultContract(typeof(ClsTestFaultContract), Action = ErrorHandlerConstant.FaultAction)]
    Int32 RegistrarTransacao(String Param1, String Param2, String Param3, Int32 Param4);
    [OperationContract]
    [FaultContract(typeof(ClsTestFaultContract), Action = ErrorHandlerConstant.FaultAction)]
    void ConfirmarTransacao(String Param1, String Param2, Int32 Param3, String Param4, String Param5);
    [OperationContract]
    [FaultContract(typeof(ClsTestFaultContract), Action = ErrorHandlerConstant.FaultAction)]
    void CancelarTransacao(String Param1, String Param2, String Param3, Int32 Param4, String Param5 = "");
  }
}

我已经浪费了无数个小时,而且我似乎无法弄清楚发生了什么破坏了我的错误处理,但效果很好。 非常感谢您的帮助

编辑

在获得帮助后,我将在工作代码下方发布。再次感谢... 以下是正确的错误处理程序:

namespace company.Test.appserver.implementation
{
  public class ServiceErrorHandlerBehaviorExtensionElement : BehaviorExtensionElement
  {
    public override Type BehaviorType
    {
      get { return typeof(TestErrorHandler); }
    }

    protected override object CreateBehavior()
    {
      return new TestErrorHandler();
    }
  }

  public class TestErrorHandler : ServiceErrorHandlerBehaviorExtensionElement, IErrorHandler, IServiceBehavior
  {
    public bool HandleError(Exception error)
    {
      return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
      if (!(error is FaultException))
      {
        ClsTestFaultContract exContract = new ClsTestFaultContract();

        FaultException<ClsTestFaultContract> fex = 
          new FaultException<ClsTestFaultContract>(exContract, exContract.DescricaoErro,
            new FaultCode(Convert.ToString(exContract.CodigoErro)));
        MessageFault msgFault = fex.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, ErrorHandlerConstant.FaultAction); 
      }
    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
      foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
      {
        ChannelDispatcher cd = cdb as ChannelDispatcher;

        if (cd != null)
        {
          cd.ErrorHandlers.Add(this);
        }
      }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
      foreach (var svcEndpoint in serviceDescription.Endpoints)
      {
        if (svcEndpoint.Contract.Name != "IMetadataExchange")
        {
          foreach (var opDesc in svcEndpoint.Contract.Operations)
          {
            if (opDesc.Faults.Count == 0)
            {
              string msg = string.Format("");
            }
          }
        }
      }
    }
  }
}

下面是正确的 web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="ServiceErrorHandler" type="company.Test.appserver.implementation.ServiceErrorHandlerBehaviorExtensionElement, TestAppServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
    <bindings>
      <basicHttpBinding>
        <binding name="SimpleBinding" />
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="DefaultBehavior" name="company.Test.appserver.implementation.TestUpdate">
        <endpoint address="udt" binding="basicHttpBinding" bindingConfiguration="SimpleBinding"
          name="TestUpdate" bindingNamespace="http://company/Test/update/2011/04"
          contract="company.Test.appserver.interfaces.ITestUpdate" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
          name="TestUpdateMex" bindingNamespace="http://company/Test/update/2011/04"
          contract="IMetadataExchange" />
      </service>
      <service behaviorConfiguration="DefaultBehavior" name="company.Test.appserver.implementation.TestTransaction">
        <endpoint address="udt" binding="basicHttpBinding" bindingConfiguration="SimpleBinding"
          name="TestTransacao" bindingNamespace="http://company/Test/transaction/2011/04"
          contract="company.Test.appserver.interfaces.ITestTransacao" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
          name="TestTransacaoMex" bindingNamespace="http://company/Test/transaction/2011/04"
          contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetBinding="webHttpBinding"
            httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <ServiceErrorHandler />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpGetBinding="webHttpBinding"
            httpGetBindingConfiguration="" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <ServiceErrorHandler />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

最佳答案

您的配置文件注册了 ServiceErrorHandler 行为扩展,但实际上并未在 下的任何集合中使用它。

关于wcf - IErrorHandler 未被绑定(bind),且未处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5789534/

相关文章:

wcf - 如何防止在WCF客户端中生成 'Specified'属性?

java - 运行测试用例时出现以下异常

jsf - 如何在jsf中创建错误页面?

c# - wcf rest ierrorhandler webfaultexception

c# - 无法让全局错误处理程序在我的自托管 wcf 服务上工作

c# - IErrorHandler 在 HTTP 状态代码为 401 Unauthorized 时返回错误的消息正文

winforms - 在应用程序中打开太多线程是否不好?

c# - 具有 WCF 通信的 Service Fabric 可靠服务

c# - 如何从 WCF asmx C# 获取客户端的计算机名称?

c++ - std::cin 不会在输入错误时抛出异常