/// <summary>
/// WCF服務端異常處理器
/// </summary>
public class WCF_ExceptionHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}html
public void ProvideFault(Exception ex, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message msg)
{ide
//
//在這裏處理服務端的消息,將消息寫入服務端的日誌
//
string err = string.Format("調用WCF接口 '{0}' 出錯", ex.TargetSite.Name) + ",詳情:\r\n" + ex.Message;
Logger.LOG_ERROR.Error(err + ",ex=" + ex);
var newEx = new FaultException(err);spa
MessageFault msgFault = newEx.CreateMessageFault();
msg = Message.CreateMessage(version, msgFault, newEx.Action);
}
}日誌
/// <summary>
/// WCF服務類的錯誤的特性
/// </summary>
public class WCF_ExceptionBehaviourAttribute : Attribute, IServiceBehavior
{
private readonly List<Type> _errorHandlerTypelist;orm
/// <summary>
/// 注入單個的錯誤事件
/// </summary>
/// <param name="errorHandlerType"></param>
public WCF_ExceptionBehaviourAttribute(Type errorHandlerType)
{
_errorHandlerTypelist = new List<Type>() { errorHandlerType };
}
/// <summary>
/// 注入多個的自定義錯誤
/// </summary>
/// <param name="errorHandlerTypelist"></param>
public WCF_ExceptionBehaviourAttribute(List<Type> errorHandlerTypelist)
{
_errorHandlerTypelist = errorHandlerTypelist;
}htm
#region IServiceBehavior Members
/// <summary>
/// 驗證服務主機和服務描述
/// </summary>
/// <param name="description"></param>
/// <param name="serviceHostBase"></param>
public void Validate(ServiceDescription description,
ServiceHostBase serviceHostBase)
{
Logger.LOG_INFO.Info(description.Name + "開啓WCF異常捕獲監聽");
}blog
/// <summary>
/// 綁定參數
/// </summary>
/// <param name="description"></param>
/// <param name="serviceHostBase"></param>
/// <param name="endpoints"></param>
/// <param name="parameters"></param>
public void AddBindingParameters(ServiceDescription description,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection parameters)
{
}
/// <summary>
/// 應用調度-更改運行時屬性值或插入自定義的功能
/// </summary>
/// <param name="description"></param>
/// <param name="serviceHostBase"></param>
public void ApplyDispatchBehavior(ServiceDescription description,
ServiceHostBase serviceHostBase)
{
if (_errorHandlerTypelist != null)
{
foreach (var _errorHandlerType in _errorHandlerTypelist)
{
var handler =
(IErrorHandler)Activator.CreateInstance(_errorHandlerType);接口
foreach (ChannelDispatcherBase dispatcherBase in
serviceHostBase.ChannelDispatchers)
{
var channelDispatcher = dispatcherBase as ChannelDispatcher;
if (channelDispatcher != null)
channelDispatcher.ErrorHandlers.Add(handler);
}
}事件
}
}ip
#endregion
}
使用
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[WCF_ExceptionBehaviour(typeof(WCF_ExceptionHandler))]
public class AccountModuleService : IAccountModuleService
{
}
若是WCF多,添加到Base裏面便可,不用每一個wcf都加,有一個Base類添加一遍就能夠了。
引用地址:轉至博客:J.Y