IErrorHandler 似乎没有处理 WCF 中的错误..有什么想法吗?

发布于 2024-09-05 12:56:42 字数 4705 浏览 10 评论 0原文

一直在阅读 IErrorHandler 并想要走配置路线。 因此,我阅读了以下内容以尝试实现它。

MSDN

关于类型定义的 Keyvan Nayyeri 博客

Rory Primrose Blog

这基本上只是包装在继承 IErrorHandler 和 IServiceBehaviour 的类中的 msdn 示例...然后它被包装在继承自 BehaviourExtensionElement 的 Extension 元素中,据称允许我将该元素添加到 web.config 中。我错过了什么?

我已经编译了它,并且从我修复的各种错误来看,WCF 实际上正在加载错误处理程序。我的问题是,我在错误处理程序中抛出来处理的异常没有得到传递给它的异常。

我的服务实现只是调用另一个类上抛出 ArgumentOutOfRangeException 的方法 - 但是处理程序永远不会处理此异常。

我的 web.config

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basic">
          <security mode="None" />                      
        </binding>
      </basicHttpBinding>
    </bindings>
    <extensions>
      <behaviorExtensions>
        <add name="customHttpBehavior"
             type="ErrorHandlerTest.ErrorHandlerElement, ErrorHandlerTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
    <behaviors>
      <serviceBehaviors>
        <behavior name="exceptionHandlerBehaviour">          
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <customHttpBehavior />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="exceptionHandlerBehaviour" name="ErrorHandlerTest.Service1">
        <endpoint binding="basicHttpBinding" bindingConfiguration="basic" contract="ErrorHandlerTest.IService1" />
      </service>
    </services>

服务契约

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(GeneralInternalFault))]
    string GetData(int value);
}

ErrorHandler 类

public class ErrorHandler : IErrorHandler , IServiceBehavior 
{
    public bool HandleError(Exception error)
    {
        Console.WriteLine("caught exception {0}:",error.Message );
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
       if (fault!=null )
       {
           if (error is ArgumentOutOfRangeException )
           {
               var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault("general internal fault."));
               MessageFault mf = fe.CreateMessageFault();

               fault = Message.CreateMessage(version, mf, fe.Action);

           }
           else
           {
               var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault(" the other general internal fault."));
               MessageFault mf = fe.CreateMessageFault();

               fault = Message.CreateMessage(version, mf, fe.Action);
           }
       }
    }

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

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        IErrorHandler errorHandler = new ErrorHandler();
        foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
            if (channelDispatcher != null)
            {
                channelDispatcher.ErrorHandlers.Add(errorHandler);
            }
        }
    }


    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {


    }
}

和行为扩展元素

    public class ErrorHandlerElement : BehaviorExtensionElement 
    {
        protected override object CreateBehavior()
        {
            return new ErrorHandler();
        }

        public override Type BehaviorType
        {
            get { return typeof(ErrorHandler); }
        }
    }

Have been reading around on IErrorHandler and want to go the config route.
so, I have read the following in an attempt to implement it.

MSDN

Keyvan Nayyeri blog about the type defintion

Rory Primrose Blog

This is basically just the msdn example wrapped in a class that inherits IErrorHandler and IServiceBehaviour ... then this is wrapped in the Extension element that inherits from BehaviourExtensionElement to allegedly allow me to add the element into the web.config. What have i missed?

I have got it to compile and from the various errors i have fixed it seems like WCF is actually loading the error handler. My problem is that the exception that i am throwing to handle in the error handler doesn;t get the exception passed to it.

My service implementation simply calls a method on another class that throws ArgumentOutOfRangeException - however this exception never gets handled by the handler.

My web.config

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basic">
          <security mode="None" />                      
        </binding>
      </basicHttpBinding>
    </bindings>
    <extensions>
      <behaviorExtensions>
        <add name="customHttpBehavior"
             type="ErrorHandlerTest.ErrorHandlerElement, ErrorHandlerTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </behaviorExtensions>
    </extensions>
    <behaviors>
      <serviceBehaviors>
        <behavior name="exceptionHandlerBehaviour">          
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <customHttpBehavior />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="exceptionHandlerBehaviour" name="ErrorHandlerTest.Service1">
        <endpoint binding="basicHttpBinding" bindingConfiguration="basic" contract="ErrorHandlerTest.IService1" />
      </service>
    </services>

Service Contract

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(GeneralInternalFault))]
    string GetData(int value);
}

The ErrorHandler class

public class ErrorHandler : IErrorHandler , IServiceBehavior 
{
    public bool HandleError(Exception error)
    {
        Console.WriteLine("caught exception {0}:",error.Message );
        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
       if (fault!=null )
       {
           if (error is ArgumentOutOfRangeException )
           {
               var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault("general internal fault."));
               MessageFault mf = fe.CreateMessageFault();

               fault = Message.CreateMessage(version, mf, fe.Action);

           }
           else
           {
               var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault(" the other general internal fault."));
               MessageFault mf = fe.CreateMessageFault();

               fault = Message.CreateMessage(version, mf, fe.Action);
           }
       }
    }

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

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        IErrorHandler errorHandler = new ErrorHandler();
        foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
        {
            ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
            if (channelDispatcher != null)
            {
                channelDispatcher.ErrorHandlers.Add(errorHandler);
            }
        }
    }


    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {


    }
}

And the Behaviour Extension Element

    public class ErrorHandlerElement : BehaviorExtensionElement 
    {
        protected override object CreateBehavior()
        {
            return new ErrorHandler();
        }

        public override Type BehaviorType
        {
            get { return typeof(ErrorHandler); }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下客 2024-09-12 12:56:42

这是一个完整的工作示例:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    string GetData(int value);
}

[DataContract]
public class MyFault
{

}

public class Service1 : IService1
{
    public string GetData(int value)
    {
        throw new Exception("error");
    }
}

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

    public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
    {
        var vfc = new MyFault();
        var fe = new FaultException<MyFault>(vfc);
        var fault = fe.CreateMessageFault();
        msg = Message.CreateMessage(version, fault, "http://ns");
    }
}

public class ErrorHandlerExtension : BehaviorExtensionElement, IServiceBehavior
{
    public override Type BehaviorType
    {
        get { return GetType(); }
    }

    protected override object CreateBehavior()
    {
        return this;
    }

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

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

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        IErrorHandler errorHandlerInstance = GetInstance();
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            dispatcher.ErrorHandlers.Add(errorHandlerInstance);
        }
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
        {
            if (endpoint.Contract.Name.Equals("IMetadataExchange") &&
                endpoint.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
                continue;

            foreach (OperationDescription description in endpoint.Contract.Operations)
            {
                if (description.Faults.Count == 0)
                {
                    throw new InvalidOperationException("FaultContractAttribute not found on this method");
                }
            }
        }
    }
}

和 web.config:

<system.serviceModel>
  <services>
    <service name="ToDD.Service1">
      <endpoint address=""
                binding="basicHttpBinding"
                contract="ToDD.IService1" />
    </service>
  </services>

  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
        <errorHandler />
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <extensions>
    <behaviorExtensions>
      <add name="errorHandler"
            type="ToDD.ErrorHandlerExtension, ToDD, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </behaviorExtensions>
  </extensions>

</system.serviceModel>

Here's a full working example:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(MyFault))]
    string GetData(int value);
}

[DataContract]
public class MyFault
{

}

public class Service1 : IService1
{
    public string GetData(int value)
    {
        throw new Exception("error");
    }
}

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

    public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
    {
        var vfc = new MyFault();
        var fe = new FaultException<MyFault>(vfc);
        var fault = fe.CreateMessageFault();
        msg = Message.CreateMessage(version, fault, "http://ns");
    }
}

public class ErrorHandlerExtension : BehaviorExtensionElement, IServiceBehavior
{
    public override Type BehaviorType
    {
        get { return GetType(); }
    }

    protected override object CreateBehavior()
    {
        return this;
    }

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

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

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        IErrorHandler errorHandlerInstance = GetInstance();
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            dispatcher.ErrorHandlers.Add(errorHandlerInstance);
        }
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
        {
            if (endpoint.Contract.Name.Equals("IMetadataExchange") &&
                endpoint.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
                continue;

            foreach (OperationDescription description in endpoint.Contract.Operations)
            {
                if (description.Faults.Count == 0)
                {
                    throw new InvalidOperationException("FaultContractAttribute not found on this method");
                }
            }
        }
    }
}

and web.config:

<system.serviceModel>
  <services>
    <service name="ToDD.Service1">
      <endpoint address=""
                binding="basicHttpBinding"
                contract="ToDD.IService1" />
    </service>
  </services>

  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
        <errorHandler />
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <extensions>
    <behaviorExtensions>
      <add name="errorHandler"
            type="ToDD.ErrorHandlerExtension, ToDD, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </behaviorExtensions>
  </extensions>

</system.serviceModel>
南汐寒笙箫 2024-09-12 12:56:42

您可以通过向 ApplyDispatchBehavior 添加打印或断点来查看 web.config 是否正在工作和加载,并查看在服务首次打开时是否打印/命中。那么它正在加载吗?

我还会在 ProvideFault 处添加一个打印/断点。

You can see if the web.config is working and loading by adding a print or a breakpoint to the ApplyDispatchBehavior, and see if that gets printed/hit when the service first opens. So is it being loaded?

I'd add a print/breakpoint at ProvideFault, as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文