IErrorHandler

/// <summary>
/// WCF服务端异常处理器
/// </summary>
public class WCF_ExceptionHandler : IErrorHandler
{
   #region IErrorHandler Members

   /// <summary>
   /// HandleError
   /// </summary>
   /// <param name="ex">ex</param>
   /// <returns>true</returns>
   public bool HandleError(Exception ex)
   {
      return true;
   }

   /// <summary>
   /// ProvideFault
   /// </summary>
   /// <param name="ex">ex</param>
   /// <param name="version">version</param>
   /// <param name="msg">msg</param>
   public void ProvideFault(Exception ex, MessageVersion version, ref Message msg)
   {
      //
      //在这里处理服务端的消息,将消息写入服务端的日志
      //
      string err = string.Format("调用WCF接口 ‘{0}‘ 出错", ex.TargetSite.Name) ",详情:\r\n" ex.Message;
      var newEx = new FaultException(err);

      MessageFault msgFault = newEx.CreateMessageFault();
      msg = Message.CreateMessage(version, msgFault, newEx.Action);
   }

   #endregion
}

  

/// <summary>
/// WCF服务类的特性
/// </summary>
public class WCF_ExceptionBehaviourAttribute : Attribute, IServiceBehavior
{
   private readonly Type _errorHandlerType;

   public WCF_ExceptionBehaviourAttribute(Type errorHandlerType)
   {
      _errorHandlerType = errorHandlerType;
   }

   #region IServiceBehavior Members

   public void Validate(ServiceDescription description,
   ServiceHostBase serviceHostBase)
   {
   }

   public void AddBindingParameters(ServiceDescription description,
   ServiceHostBase serviceHostBase,
   Collection<ServiceEndpoint> endpoints,
   BindingParameterCollection parameters)
   {
   }

   public void ApplyDispatchBehavior(ServiceDescription description,
   ServiceHostBase serviceHostBase)
   {
      var handler =
      (IErrorHandler)Activator.CreateInstance(_errorHandlerType);

      foreach (ChannelDispatcherBase dispatcherBase in
      serviceHostBase.ChannelDispatchers)
      {
         var channelDispatcher = dispatcherBase as ChannelDispatcher;
         if (channelDispatcher != null)
         channelDispatcher.ErrorHandlers.Add(handler);
      }
   }

   #endregion
}

  [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[WCF_ExceptionBehaviour(typeof(WCF_ExceptionHandler))]
public class AccountModuleService : IAccountModuleService
{
   
   //来源:C/S框架网(www.csframework.com) QQ:1980854898

}

public class GlobalException : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            //服务器端能够获取到错误方法
            var ex = new FaultException(string.Format("Wcf错误接口方法{0}", error.TargetSite.Name));
            MessageFault mf = ex.CreateMessageFault();
            //fault = Message.CreateMessage(version, mf, ex.Action);
        }
    }

 public class GlobalExceptionHandlerBehaviourAttribute : Attribute, IServiceBehavior
    {
        private Type _Type;

        public GlobalExceptionHandlerBehaviourAttribute(Type ExcepType)
        {
            this._Type = ExcepType;
        }

        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)
        {
            var Handle = (IErrorHandler)Activator.CreateInstance(_Type);
            foreach (ChannelDispatcherBase dispatcherBase in
                serviceHostBase.ChannelDispatchers)
            {
                var channelDispatcher = dispatcherBase as ChannelDispatcher;
                if (channelDispatcher != null)
                    channelDispatcher.ErrorHandlers.Add(Handle);
            }
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }
    }

[GlobalExceptionHandlerBehaviour(typeof(GlobalException))]
    public class LoginService : ILoginContract
    {

        public string Login(string UserName, string UserPwd)
        {
            if (string.IsNullOrEmpty(UserPwd))
            {
                throw new Exception();
            }
            return UserName;
        }
    }

 public class Network
    {
        [DllImport("wininet")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

        /// <summary>
        /// 检测本机是否联网
        /// </summary>
        /// <returns></returns>
        public static bool IsConnectedInternet()
        {
            int i = 0;
            if (InternetGetConnectedState(out i, 0))
            {
                //已联网
                return true;
            }
            else
            {
                //未联网
                return false;
            }

        }

        private static bool? IsInit = null;
        static Thread th = null;

        private static NetworkDelegate OnClose = null;

        ~Network()
        {

            if (OnClose != null) OnClose();
        }

        /// <summary>
        /// 检测本机是否已经联网
        /// </summary>
        /// <param name="StartType"></param>
        /// <param name="CheckTime"></param>
        /// <param name="AllTime"></param>
        /// <returns></returns>
        public static void Start(NetworkStartTypeEnum StartType, TimeSpan CheckTime, int AllTime)
        {
            th = new Thread(() =>
            {
                while (true)
                {
                    bool Content = IsConnectedInternet();
                    if(IsInit==null)IsInit = Content;
                    if (Content == false && IsInit == true)
                    {
                        OnUnConnection();
                    }
                    else if (Content == true && IsInit == false)
                    {
                        OnConnection();
                    }
                    IsInit = Content;
                    Thread.Sleep(CheckTime);
                }
            });
            th.IsBackground = true;
            OnClose += () =>
            {
                try
                {
                    th.Abort();
                }
                catch { }
            };
            th.Start();
            if (StartType == NetworkStartTypeEnum.JustTime)
            {
                Thread closeThread = new Thread(() =>
                {
                    Thread.Sleep(AllTime);
                });
                closeThread.IsBackground = true;
                OnClose += () =>
                {
                    try
                    {
                        closeThread.Abort();
                    }
                    catch { }
                };
                closeThread.Start();
            }
        }
        //本地委托
        public delegate void NetworkDelegate();

        /// <summary>
        /// 当连上网的时候
        /// </summary>
        public static event NetworkDelegate OnConnection;
        /// <summary>
        /// 当没连上的时候
        /// </summary>
        public static event NetworkDelegate OnUnConnection;
    }
    public enum NetworkStartTypeEnum{
        ApplicationExit,
        JustTime
    }

  

   public class ServiceErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            FaultException<string> fex = new FaultException<string>(error.Message);
            MessageFault mf = fex.CreateMessageFault();
            fault = Message.CreateMessage(version, mf, "http://zh-ja-demo/svfault");
        }
    }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
    public class MyContractBehaviorAttribute : Attribute, IContractBehavior
    {
        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            ServiceErrorHandler sverr = new ServiceErrorHandler();
            dispatchRuntime.ChannelDispatcher.ErrorHandlers.Add(sverr);
        }

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }
    }

//--------------------------------------------------------

    [FaultContract(typeof(string), Action = "http://zh-ja-demo/svfault")]
        long RunWork(int bs);

  

时间: 2024-10-10 12:18:09

IErrorHandler的相关文章

【WCF】自定义错误处理(IErrorHandler接口的用法)

当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调用中,action标头比较重要,它是塞在SOAP消息的Headers元素下面的,是消息头的一部分,action用来对服务操作进行定义的.用小学生能听懂的话说,就是某个服务操作的“学号”,通道层在消息调度时,会根据它来寻找要调用的Operation.记得老周举过例子,就好比你去王老板家里,你得知道王老

【WCF】错误处理(四):一刀切——IErrorHandler

前面几篇烂文中所介绍到的错误方式,都是在操作协定的实现代码中抛出 FaultException 或者带泛型参数的detail方案,有些时候,错误的处理方法比较相似,可是要每个操作协定去处理,似乎也太麻烦,此时就应当考虑统一处理了. 在 System.ServiceModel.Dispatcher 命名空间下,有一个 IErrorHandler 接口,这个接口就是让我们统一处理错误的. 先来认识一下这个接口. public interface IErrorHandler { bool Handle

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

在处理WCF异常的时候,有大概几种方式: 第一种是在配置文件中,将includeExceptionDetailInFaults设置为true <behavior name="serviceDebuBehavior"><serviceDebug includeExceptionDetailInFaults="true" /></behavior> 但是这种方式会导致敏感信息泄漏的危险,一般我们仅仅在调试的时候才开启该属性,如果已经发

Useful WCF Behaviors - IErrorHandler

Behaviors in WCF are so stinking useful, and once you get past the basics of WCF they're arguably a necessity. Microsoft has saved itself from hundreds of hours of cursing by including the ability to define custom behaviors. My favorite use of behavi

WCF异常处理

[读书笔记] 在进行分布式应用的异常处理时需要解决和考虑的基本要素: 异常的封装:服务端抛出的异常如何序列化传递到客户端 敏感信息的屏蔽:抛出的异常往往包含一些敏感的信息,直接将服务操作执行过程抛出的异常信息抛出到客户端,存在极大风险 系统的集成和互操作:基于不同厂商和技术平台系统之间的有效集成和互操作也给异常处理提出了新的要求,基于平台A的服务队异常的描述弱项被基于平台B的客户端理解,需要按照一种厂商中立的标准来规范对异常的描述 1. 异常处理模式 异常从服务端抛出 异常类型:应用异常(App

WCF服务全局统一异常处理机制

转载:http://www.csframework.com/archive/1/arc-1-20150109-2193.htm 服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常,将统一调用WCF_ExceptionHandler.ProvideFault方法,因此不需要每个方法使用try catch写法. C# Code: /// <summary> /// WCF服务端异常处理器 /// </summary> public class WCF_Excepti

收藏2篇关于WCF异常处理的文章

WCF Extensibility – IErrorHandler Exception Handling in WCF Web Service收藏2篇关于WCF异常处理的文章,码迷,mamicode.com

服务端增加WCF服务全局异常处理机制

转自:http://www.csframework.com/archive/1/arc-1-20150109-2193.htm 服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常,将统一调用WCF_ExceptionHandler.ProvideFault方法,因此不需要每个方法使用try catch写法. 1 /// <summary> 2 /// WCF服务端异常处理器 3 /// </summary> 4 public class WCF_Exceptio

WCF Extensibility

Over the next months I intend on writing a series of posts about the (many) extensibility points from WCF (up to .NET Framework 4.0). The cadence should be around one new post every 1-2 weeks (depending on the workload I have at work). WCF is a very