使用IErrorHandler
接口来扩展您的服务。
这将允许您为任何异常提供适当的故障。
这篇文章展示了如何将您自己的错误处理程序连接到您的服务行为。
我个人使用单个类来实现所有必要的元素,如下所示:
public class ErrorSavingServiceBahavior : BehaviorExtensionElement, IServiceBehavior, IErrorHandler
{
private string m_sHostName;
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
this.m_sHostName = serviceHostBase.Description.Name;
foreach (ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
{
if (!chanDisp.ErrorHandlers.Contains(this))
{
chanDisp.ErrorHandlers.Add(this);
}
}
}
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
public bool HandleError(Exception error)
{
//my custom code
}
public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
//my custom code
}
public override Type BehaviorType
{
get { return this.GetType(); }
}
protected override object CreateBehavior()
{
return this;
}
}
和 web.config 我扩展:
<behaviors>
<serviceBehaviors>
<behavior name="BehaviorName">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true"/>
<saveExceptions />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add
name="saveExceptions"
type="Namespace.Class, DLLName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
/>
</behaviorExtensions>
</extensions>