我们将企业库异常处理块与 ELMAH 结合使用来记录异常。它不使用任何 HTTP 模块,而是直接调用日志到 ELMAH。
public class ErrorHandlerServiceBehaviour : BehaviorExtensionElement, IServiceBehavior
{
#region BehaviourExtensionElement Members
public override Type BehaviorType
{
get { return typeof(ErrorHandlerServiceBehaviour); }
}
protected override object CreateBehavior()
{
return new ErrorHandlerServiceBehaviour();
}
#endregion
#region IServiceBehavior Members
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
channelDispatcher.ErrorHandlers.Add(new ElmahExceptionHandler());
}
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
#endregion
}
然后是异常处理程序
public class ElmahExceptionHandler : IErrorHandler
{
#region IErrorHandler Members
public bool HandleError(Exception error)
{
return ExceptionPolicy.HandleException(error, "ServiceExceptions");
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
}
#endregion
}
然后在 app.config 的企业库异常策略部分
<exceptionHandling>
<exceptionPolicies>
<add name="ServiceExceptions">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add type="DB.Framework.Logging.ElmahExceptionHandler, DinguBlue.Framework.Logging"
name="Elmah Exception Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
参见例如http://dotnetslackers.com/articles/aspnet/Getting-ELMAH-to-work-with-WCF-services.aspx