为你解决WCF异常问题

开发 后端
这里就WCF异常的问题做出了分析,也列举出了相应的解决方案,希望通过看本为对大家有技术上的提高。

WCF还是比较常用的,于是我研究了一下WCF,在这里拿出来和大家分享一下,希望对大家有用。异常消息与特定技术有关,.NET异常同样如此,因而WCF并不支持传统的异常处理方式。如果在WCF服务中采用传统的方式处理异常,由于异常消息不能被序列化,因而客户端无法收到服务抛出的WCF异常,例如这样的服务设计:

  1. [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]   
  2. public interface IDocumentsExplorerService   
  3. {   
  4. [OperationContract]   
  5. DocumentList FetchDocuments(string homeDir);   
  6. }   
  7. [ServiceBehavior(InstanceContextModeInstanceContextMode=InstanceContextMode.Single)]   
  8. public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable   
  9. {   
  10. public DocumentList FetchDocuments(string homeDir)   
  11. {   
  12. //Some Codes   
  13.  
  14. if (Directory.Exists(homeDir))   
  15. {   
  16. //Fetch documents according to homedir   
  17. }   
  18. else   
  19. {   
  20. throw new DirectoryNotFoundException(   
  21. string.Format("Directory {0} is not found.",homeDir));   
  22. }   
  23. }   
  24. public void Dispose()   
  25. {   
  26. Console.WriteLine("The service had been disposed.");   
  27. }   
  28. }   

则客户端在调用如上的服务操作时,如果采用如下的捕获方式是无法获取该WCF异常的:

  1. catch (DirectoryNotFoundException ex)   
  2. {   
  3. //handle the exception;   
  4. }   

为了弥补这一缺陷,WCF会将无法识别的异常均当作为FaultException异常对象,因此,客户端可以捕获FaultException或者Exception异常:

  1. catch (FaultException ex)   
  2. {   
  3. //handle the exception;   
  4. }   
  5. catch (Exception ex)   
  6. {   
  7. //handle the exception;   
  8. }  

#T#然而,这样捕获的WCF异常,却无法识别DirectoryNotFoundException所传递的错误信息。尤为严重的是这样的异常处理方式还会导致传递消息的通道出现错误,当客户端继续调用该服务代理对象的服务操作时,会获得一个CommunicationObjectFaultedException 异常,无法继续使用服务。如果服务被设置为PerSession模式或者Single模式,异常还会导致服务对象被释放,终止服务。

  1. [ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]   
  2. public interface IDocumentsExplorerService   
  3. {   
  4. [OperationContract]   
  5. [FaultContract(typeof(DirectoryNotFoundException))]   
  6. DocumentList FetchDocuments(string homeDir);   
  7. }   
责任编辑:田树 来源: 博客
相关推荐

2009-11-09 09:06:44

WCF端口

2009-11-05 13:08:44

WCF客户端配置

2009-12-07 18:38:16

WCF异常

2009-11-05 12:45:25

WCF异常

2009-11-05 09:29:29

WCF是什么

2009-12-08 16:30:29

WCF程序

2009-12-07 16:23:46

WCF编程

2010-02-24 14:05:08

WCF openati

2010-02-26 15:46:48

Silverlight

2009-11-06 15:25:25

WCF异常

2009-11-17 09:55:53

PHP服务器安装

2010-02-25 14:53:44

WCF调用服务异常

2009-12-08 10:52:30

WCF双工通信

2009-12-22 16:03:03

WCF异常

2010-03-02 16:34:36

WCF线程

2009-11-06 09:39:40

WCF契约

2009-11-06 12:59:56

WCF服务通信

2010-02-22 13:35:03

WCF异常处理

2009-12-08 11:05:59

2010-01-18 14:02:58

交换机DHCP服务器
点赞
收藏

51CTO技术栈公众号