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

posted @ 2018-12-14 15:53  Marco CAO  阅读(152)  评论(0编辑  收藏  举报