码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-14 17:26:40      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:mon   blank   oid   sage   cee   service   sys   https   write   

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 统一处理异常利用行为服务扩展

标签:mon   blank   oid   sage   cee   service   sys   https   write   

原文地址:https://www.cnblogs.com/marcocao/p/10119851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!