Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为WCF IErrorhandler设置web.config_Wcf_Web Config_Ierrorhandler - Fatal编程技术网

如何为WCF IErrorhandler设置web.config

如何为WCF IErrorhandler设置web.config,wcf,web-config,ierrorhandler,Wcf,Web Config,Ierrorhandler,无法使用正确的web.config将IErrorHandler集成到我的项目中 我有一个成功运行的WCF,它正被.net 4中的WebClient使用,但当试图将IErrorhandler设置为全局错误记录器作为我所有服务方法的总括时,事情很快就失败了-主要与web.config部分有关!请帮忙 这三项服务是:IReport、IServiceCustomer、IServiceUser 在名为MyErrorClass.cs的单独类中实现IErrorHandler,如下所示: namespace C

无法使用正确的web.config将IErrorHandler集成到我的项目中

我有一个成功运行的WCF,它正被.net 4中的WebClient使用,但当试图将IErrorhandler设置为全局错误记录器作为我所有服务方法的总括时,事情很快就失败了-主要与web.config部分有关!请帮忙

这三项服务是:IReport、IServiceCustomer、IServiceUser

在名为MyErrorClass.cs的单独类中实现IErrorHandler,如下所示:

namespace CustomerWcfService
{
public class WcfErrorHandler : IErrorHandler
{
   /// <summary>
    /// Enables the creation of a custom <see cref="T:System.ServiceModel.FaultException`1"/> that is returned from an exception in the course of a service method.
    /// </summary>
    /// <param name="error">The <see cref="T:System.Exception"/> object thrown in the course of the service operation.</param><param name="version">The SOAP version of the message.</param><param name="fault">The <see cref="T:System.ServiceModel.Channels.Message"/> object that is returned to the client, or service, in the duplex case.</param>
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        // can create custom error messages here
    }

    /// <summary>
    /// Enables error-related processing and returns a value that indicates whether the dispatcher aborts the session and the instance context in certain cases. 
    /// </summary>
    /// <returns>
    /// true if  should not abort the session (if there is one) and instance context if the instance context is not <see cref="F:System.ServiceModel.InstanceContextMode.Single"/>; otherwise, false. The default is false.
    /// </returns>
    /// <param name="error">The exception thrown during processing.</param>
    public bool HandleError(Exception error)
    {
        // log error to database using legacy error handler
        ErrorHandler.LogError(error);

        // Let the other ErrorHandler do their jobs
        return true;
    }
}

public class WcfErrorServiceBehaviour : IServiceBehavior
{
    /// <summary>
    /// Provides the ability to inspect the service host and the service description to confirm that the service can run successfully.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The service host that is currently being constructed.</param>
    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {   }

    /// <summary>
    /// Provides the ability to pass custom data to binding elements to support the contract implementation.
    /// </summary>
    /// <param name="serviceDescription">The service description of the service.</param><param name="serviceHostBase">The host of the service.</param><param name="endpoints">The service endpoints.</param><param name="bindingParameters">Custom objects to which binding elements have access.</param>
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {   }

    /// <summary>
    /// Provides the ability to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The host that is currently being built.</param>
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var handler = new WcfErrorHandler();
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            dispatcher.ErrorHandlers.Add(handler);
        }
    }
}

public class WcfErrorHandlerBehaviour : BehaviorExtensionElement
{
    /// <summary>
    /// Creates a behavior extension based on the current configuration settings.
    /// </summary>
    /// <returns>
    /// The behavior extension.
    /// </returns>
    protected override object CreateBehavior()  {   return new WcfErrorServiceBehaviour();  }

    /// <summary>
    /// Gets the type of behavior.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Type"/>.
    /// </returns>
    public override Type BehaviorType   {   get { return typeof (WcfErrorServiceBehaviour); }   }
}
}
    [WcfErrorServiceBehaviour]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
                     ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class MXServiceCommands : IMXServiceCommands
    {
    }
命名空间定制服务
{
公共类WcfErrorHandler:IErrorHandler
{
/// 
///启用创建从服务方法过程中的异常返回的自定义。
/// 
///在服务操作过程中抛出的对象。消息的SOAP版本。在双工情况下返回给客户端或服务的对象。
public void providefaulture(异常错误,消息版本,ref消息错误)
{
//可以在此处创建自定义错误消息
}
/// 
///启用与错误相关的处理,并返回一个值,该值指示调度器在某些情况下是否中止会话和实例上下文。
/// 
/// 
///如果不应中止会话(如果有),则为true;如果实例上下文不应中止,则为实例上下文;否则为false。默认值为false。
/// 
///处理过程中引发的异常。
公共布尔句柄错误(异常错误)
{
//使用旧错误处理程序将错误记录到数据库
ErrorHandler.LogError(错误);
//让另一个ErrorHandler完成他们的工作
返回true;
}
}
公共类服务行为:IServiceBehavior
{
/// 
///提供检查服务主机和服务描述的功能,以确认服务可以成功运行。
/// 
///服务描述。当前正在构造的服务主机。
公共无效验证(ServiceDescription ServiceDescription,ServiceHostBase ServiceHostBase)
{   }
/// 
///提供将自定义数据传递给绑定元素以支持契约实现的能力。
/// 
///服务的服务描述。服务的主机。服务端点。绑定元素可以访问的自定义对象。
public void AddBindingParameters(ServiceDescription ServiceDescription、ServiceHostBase ServiceHostBase、集合终结点、BindingParameterCollection bindingParameters)
{   }
/// 
///提供更改运行时属性值或插入自定义扩展对象(如错误处理程序、消息或参数拦截器、安全扩展和其他自定义扩展对象)的功能。
/// 
///服务描述。当前正在生成的主机。
公共无效ApplyDispatchBehavior(ServiceDescription ServiceDescription,ServiceHostBase ServiceHostBase)
{
var handler=new WcfErrorHandler();
foreach(serviceHostBase.ChannelDispatchers中的ChannelDispatcher)
{
dispatcher.ErrorHandlers.Add(处理程序);
}
}
}
公共类WcfErrorHandlerBehaviour:BehaviorExtensionElement
{
/// 
///基于当前配置设置创建行为扩展。
/// 
/// 
///行为扩展。
/// 
受保护的重写对象CreateBehavior(){返回新的WCFerrorServiceBehavior();}
/// 
///获取行为的类型。
/// 
/// 
///A。
/// 
公共重写类型行为类型{get{return typeof(wcferrorservicebehavior);}
}
}
web.config应该是什么样的呢?我已经在网上尝试了各种教程和答案的一百万种组合,但都没有成功!当我没有涉及到IErrorHandler时,web.config的原始工作摘录就是这样的

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <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" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

请有人将更正后的web.config发送给这个WCF noob,因为我一直在删除并重试,但没有得到任何结果(我已经为此浪费了很多天):(


然后将您的行为应用到您希望其应用到的服务

编辑:


很抱歉错过了,但实际上您需要删除扩展定义中类型名称中的任何换行符和任何额外空格(旧的WCF错误,它迫使您在扩展类型声明中使用完全限定的名称字符串)。

这有点晚了,但对于其他用户来说,这是一个更好的方法(在我看来)上面的代码只需要稍微修改一下

您可以更改:

    public class WcfErrorServiceBehaviour : IServiceBehavior
致:

现在,您可以将其用作服务类的属性,如下所示:

namespace CustomerWcfService
{
public class WcfErrorHandler : IErrorHandler
{
   /// <summary>
    /// Enables the creation of a custom <see cref="T:System.ServiceModel.FaultException`1"/> that is returned from an exception in the course of a service method.
    /// </summary>
    /// <param name="error">The <see cref="T:System.Exception"/> object thrown in the course of the service operation.</param><param name="version">The SOAP version of the message.</param><param name="fault">The <see cref="T:System.ServiceModel.Channels.Message"/> object that is returned to the client, or service, in the duplex case.</param>
    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        // can create custom error messages here
    }

    /// <summary>
    /// Enables error-related processing and returns a value that indicates whether the dispatcher aborts the session and the instance context in certain cases. 
    /// </summary>
    /// <returns>
    /// true if  should not abort the session (if there is one) and instance context if the instance context is not <see cref="F:System.ServiceModel.InstanceContextMode.Single"/>; otherwise, false. The default is false.
    /// </returns>
    /// <param name="error">The exception thrown during processing.</param>
    public bool HandleError(Exception error)
    {
        // log error to database using legacy error handler
        ErrorHandler.LogError(error);

        // Let the other ErrorHandler do their jobs
        return true;
    }
}

public class WcfErrorServiceBehaviour : IServiceBehavior
{
    /// <summary>
    /// Provides the ability to inspect the service host and the service description to confirm that the service can run successfully.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The service host that is currently being constructed.</param>
    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {   }

    /// <summary>
    /// Provides the ability to pass custom data to binding elements to support the contract implementation.
    /// </summary>
    /// <param name="serviceDescription">The service description of the service.</param><param name="serviceHostBase">The host of the service.</param><param name="endpoints">The service endpoints.</param><param name="bindingParameters">Custom objects to which binding elements have access.</param>
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {   }

    /// <summary>
    /// Provides the ability to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The host that is currently being built.</param>
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var handler = new WcfErrorHandler();
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            dispatcher.ErrorHandlers.Add(handler);
        }
    }
}

public class WcfErrorHandlerBehaviour : BehaviorExtensionElement
{
    /// <summary>
    /// Creates a behavior extension based on the current configuration settings.
    /// </summary>
    /// <returns>
    /// The behavior extension.
    /// </returns>
    protected override object CreateBehavior()  {   return new WcfErrorServiceBehaviour();  }

    /// <summary>
    /// Gets the type of behavior.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Type"/>.
    /// </returns>
    public override Type BehaviorType   {   get { return typeof (WcfErrorServiceBehaviour); }   }
}
}
    [WcfErrorServiceBehaviour]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
                     ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class MXServiceCommands : IMXServiceCommands
    {
    }

希望这能对其他人有所帮助。

只是一句支持的话:我们都有“不断删除并重试…”的经历。如果你发现自己的牛仔/伏都教编码时间太长而没有效果,你可能需要停下来一秒钟,阅读一下这个主题(MSDN、一本书等),而不想解决手头的问题。经常(尽管不总是:p),这样做之后,解决您遇到的问题似乎很容易。如何“将行为应用于服务”?我希望它适用于所有您没有提供服务部分,所以我没有写下来,但如果是WCF 4+,则默认情况下,使用
行为
标记(没有名称)应应用于每个服务。如果没有,则必须为每个服务设置名称您的行为并在服务标签中使用
behaviorConfiguration=yourbehaviorname
。您可能必须告诉我您的意思…但目前我收到一个错误:“元素'behavior'有一个无效的子元素'errorHandler'。需要一个可能的元素列表…等等”奇怪的是,我复制了一个