/// <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);

  

IErrorHandler的更多相关文章

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

    当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...

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

    前面几篇烂文中所介绍到的错误方式,都是在操作协定的实现代码中抛出 FaultException 或者带泛型参数的detail方案,有些时候,错误的处理方法比较相似,可是要每个操作协定去处理,似乎也太麻 ...

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

    在处理WCF异常的时候,有大概几种方式: 第一种是在配置文件中,将includeExceptionDetailInFaults设置为true <behavior name="servi ...

  4. Useful WCF Behaviors - IErrorHandler

    Behaviors in WCF are so stinking useful, and once you get past the basics of WCF they're arguably a ...

  5. 【WCF】错误协定声明

    在上一篇烂文中,老周给大伙伴们介绍了 IErrorHandler 接口的使用,今天,老周补充一个错误处理的知识点——错误协定. 错误协定与IErrorHandler接口不同,大伙伴们应该记得,上回我们 ...

  6. WCF入门(22)

    前言 本还想写一集WCF入门教程的,心情实在不好,明天又还有面试,改天再写吧. 说一下今天遇到的入职坑.面试能坑,上班能坑,完全没想到入职也能坑.切身经历. 今年10月份想换工作,更新了一下简历,接到 ...

  7. WCF 入门(20)

    前言 Happy weekend. 第20集 通过实现IErrorHandler接口来统一处理WCF里的异常 Centralized exception handling in WCF by impl ...

  8. WCF的执行过程

    既然是实现互通信.那么肯定会有概念意义上的服务端Server  和概念意义上的客户端 Client,在这里,我所说明的都是概念意义上的,单独强调此,是因为,基于WCF的通信没有物理上的划分,但是概念上 ...

  9. Wcf实现IServiceBehavior拓展机制

    IServiceBehavior接口 描述:提供一种在整个服务内修改或插入自定义拓展机制: 命名空间:  System.ServiceModel.Description程序集:  System.Ser ...

随机推荐

  1. 微信jaapi签名

    public WeiXinJsSignature(string weixinUrl) { //string url = ConfigurationManager.AppSettings["U ...

  2. Spring cloud微服务安全实战-6-9sentinel之熔断降级

    来讲一下降级规则 服务会互相调用,服务A会有一些服务之间的依赖. 假设服务D的响应时间变长了.A调用D就会卡住了. 熔断,某一个服务出现问题,会把服务拖死.如果A出现,会把依赖A的那些服务拖死. 主要 ...

  3. 123457123456#0#----com.ppGame.ChengYu43--前拼后广--成语caicaicai_pp

    com.ppGame.ChengYu43--前拼后广--成语caicaicai_pp

  4. 实现不同的项目,用不同的git 账号提交

    可以全局配置一个git 账户名和密码,然后在具体项目里单独配置一个账户名和密码 例如: git config --global user.name "winyh" git conf ...

  5. 简单明了的注解,读取CLASS中的注解

    /***********注解声明***************/ /** * 水果名称注解 * @author peida * */ @Target(ElementType.FIELD) @Reten ...

  6. [ kvm ] 学习笔记 2:虚拟化基础

    1. 虚拟化概念 什么是虚拟化 虚拟化是使用所谓虚拟机管理程序从一台物理机上创建若干个虚拟机的过程.虚拟机的行为和运转方式与物理机一样,但它们会使用物理机的计算资源,如 CPU .内存和存储.虚拟机管 ...

  7. 【分布式一致性】etcd

    etcd: https://jimmysong.io/kubernetes-handbook/concepts/etcd.html 什么是 分布式一致性: http://thesecretliveso ...

  8. Win10下载安装PostgreSQL 11.1

    下载地址:https://get.enterprisedb.com/postgresql/postgresql-11.1-1-windows-x64.exe Installation Director ...

  9. 【Leetcode_easy】1037. Valid Boomerang

    problem 1037. Valid Boomerang 参考 1. Leetcode_easy_1037. Valid Boomerang; 完

  10. Winsock.简单TCP

    PS:vs2017 编译C++代码 支持 XP:项目属性-->链接器-->系统-->需要的最小版本--> 输入 "5.1" 1.ZC:测试:c向s 发送长度 ...