WCF还是比较常用的,于是我研究了一下WCF,在这里拿出来和大家分享一下,希望对大家有用。异常消息与特定技术有关,.NET异常同样如此,因而WCF并不支持传统的异常处理方式。如果在WCF服务中采用传统的方式处理异常,由于异常消息不能被序列化,因而客户端无法收到服务抛出的WCF异常,例如这样的服务设计:
[ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]
public interface IDocumentsExplorerService
{
[OperationContract]
DocumentList FetchDocuments(string homeDir);
}
[ServiceBehavior(InstanceContextModeInstanceContextMode=InstanceContextMode.Single)]
public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable
{
public DocumentList FetchDocuments(string homeDir)
{
//Some Codes
if (Directory.Exists(homeDir))
{
//Fetch documents according to homedir
}
else
{
throw new DirectoryNotFoundException(
string.Format("Directory {0} is not found.",homeDir));
}
}
public void Dispose()
{
Console.WriteLine("The service had been disposed.");
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
则客户端在调用如上的服务操作时,如果采用如下的捕获方式是无法获取该WCF异常的:
catch (DirectoryNotFoundException ex)
{
//handle the exception;
}
- 1.
- 2.
- 3.
- 4.
为了弥补这一缺陷,WCF会将无法识别的异常均当作为FaultException异常对象,因此,客户端可以捕获FaultException或者Exception异常:
catch (FaultException ex)
{
//handle the exception;
}
catch (Exception ex)
{
//handle the exception;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
#T#然而,这样捕获的WCF异常,却无法识别DirectoryNotFoundException所传递的错误信息。尤为严重的是这样的异常处理方式还会导致传递消息的通道出现错误,当客户端继续调用该服务代理对象的服务操作时,会获得一个CommunicationObjectFaultedException 异常,无法继续使用服务。如果服务被设置为PerSession模式或者Single模式,异常还会导致服务对象被释放,终止服务。
[ServiceContract(SessionModeSessionMode = SessionMode.Allowed)]
public interface IDocumentsExplorerService
{
[OperationContract]
[FaultContract(typeof(DirectoryNotFoundException))]
DocumentList FetchDocuments(string homeDir);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.