如何为WCF IErrorhandler设置web.config

时间:2012-09-14 14:15:04

标签: wcf web-config ierrorhandler

无法使用正确的web.config

将IErrorHandler集成到我的项目中

我有一个成功运行的WCF,正在被.net 4中的webclients使用但是当我尝试将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); }   }
}
}

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>

请有人发送此WCF noob更正了web.config,因为我一直在删除并再次尝试并且没有在哪里(我已经失去了这么多天):(

2 个答案:

答案 0 :(得分:15)

<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" />
        <errorHandler/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  <extensions>
    <behaviorExtensions>
      <add name="errorHandler" type="CustomerWcfService.WcfErrorHandlerBehaviour, CustomerWcfService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
    </behaviorExtensions>
  </extensions>
</system.serviceModel>

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

编辑:

对不起,但实际上您需要删除扩展定义中类型名称中的任何换行符和任何其他空格(旧的WCF错误会强制您在扩展类型声明中使用完全限定的名称字符串)

答案 1 :(得分:8)

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

您可以更改:

    public class WcfErrorServiceBehaviour : IServiceBehavior

为:

    public class WcfErrorServiceBehaviourAttribute : Attribute, IServiceBehavior

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

    [WcfErrorServiceBehaviour]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
                     ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class MXServiceCommands : IMXServiceCommands
    {
    }

希望这有助于其他人。