WCF 统一处理异常利用行为服务扩展

Posted marcocao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WCF 统一处理异常利用行为服务扩展相关的知识,希望对你有一定的参考价值。

https://www.cnblogs.com/niaowo/p/4727378.html

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace WcfService1.Common
{
    public class ErrorHandler : System.ServiceModel.Dispatcher.IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return false;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (error == null)
                return;
            if (HttpContext.Current == null) //In case we run outside of IIS
                return;
            //Elmah.ErrorSignal.FromCurrentContext().Raise(error);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace WcfService1.Common
{
    public class ServiceErrorBehaviorAttribute : Attribute, IServiceBehavior
    {
        Type _errorHandlerType;
        public ServiceErrorBehaviorAttribute(Type errorHandlerType)
        {
            this._errorHandlerType = errorHandlerType;
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            Console.WriteLine("Inside {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            IErrorHandler errorHandler = (IErrorHandler)Activator.CreateInstance(_errorHandlerType);

            foreach (var dispatcher in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher cd = dispatcher as ChannelDispatcher;
                cd.ErrorHandlers.Add(errorHandler);
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            Console.WriteLine("Inside {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }
    }
}

 

使用

[ServiceErrorBehaviorAttribute(typeof(ErrorHandler))]
public class Service1 : IService1

以上是关于WCF 统一处理异常利用行为服务扩展的主要内容,如果未能解决你的问题,请参考以下文章

.NET WCF 异常

异常的 WCF 客户端行为

利用Attribute和IErrorHandler处理WCF全局异常

使用代码而不是配置文件将消息检查器添加到 WCF 服务

WCF 异常处理策略

从 WCF 4 REST 模板获取调试输出