/// <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. js 解析 JSON 数据

    JSON 数据如下: { "name": "mkyong", , "address": { "streetAddress" ...

  2. [原]Arcgis arcmap修改图元配色

    感谢南师大的“深爱”提供的帮助 1.选择识别工具,点击海洋,确定海洋色块的color index为255 2.右键tif选择属性 3.选择分页栏中的符号化(Symbology) 4.找到对应的Labe ...

  3. 转「服务器运维」如何解决服务器I/O过高的问题

    问题缘起: 当我习惯性地用top查看任务运行状态时,发现我运行的100个任务,只有3个在运行,其他都在摸鱼状态.同时发现我的任务进程都是"D"状态(未截图),而不是R(运行)状态. ...

  4. WPF ContextMenu DataTemplate MenuItem Visibility 问题

    问题: ContextMenu 的 DataTemplate 中 MenuItem 设置 Visibility 不起作用 需要添加一下样式才可以: <ContextMenu.ItemContai ...

  5. opencv3.4.6 cmake

    Selecting Windows SDK version to target Windows 10.0.16299. Found PythonInterp: N:/Anaconda3/install ...

  6. Django中的ModelForm与Form

    django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm. 关于django中的表单系统有两种: 基于django.forms.Form 基于dj ...

  7. django 中单独执行py文件修改用户名

    Python文件代码 import os import django # 在environ字典里设置默认Django环境,'xxxx.settings'指Django项目的配置文件 os.enviro ...

  8. BladeX部署说明(win7)

    一:安装jdk-8u221-windows-x64 二:安装Nacos,解压nacos-server-1.0.0,运行bin目录下的startup.cmd,成功可以用浏览器访问:localhost:8 ...

  9. google浏览器插件开发教程

    谷歌插件开发之notifications通知API全解析https://blog.csdn.net/WU5229485/article/details/82012167浏览器API大全https:// ...

  10. 【深度学习框架-caffe】caffe中使用到的layer

    https://www.jianshu.com/p/f6f49f6bcea6 https://github.com/BVLC/caffe/tree/master/include/caffe/layer ...