处理WCF异常问题的方法
在WCF中,如果没有指定,服务端的异常不会传递到客户端,如:在等于0时,客户端根本不知道异常的原因据,也即"Divsion by zero!"异常信息不会传到客户端。
[ServiceContract]
publicclassCalculatorService
{
[OperationContract]
intDivide(inta,intb)
{
if(b==0)thrownewException(“Divisionbyzero!”);
returna/b;
}
}
publicclassCalculatorService
{
[OperationContract]
intDivide(inta,intb)
{
if(b==0)thrownewException(“Divisionbyzero!”);
returna/b;
}
}
在最简单的情况下,我们可以使用空FaultException(它只包含一个string字符串,称为错误原因), 如下所示:
[ServiceContract]
publicclassCalculatorService
{
[OperationContract]
intDivide(inta,intb)
{
if(b==0)thrownewFaultException(“Divisionbyzero!”);
returna/b;
}
}
publicclassCalculatorService
{
[OperationContract]
intDivide(inta,intb)
{
if(b==0)thrownewFaultException(“Divisionbyzero!”);
returna/b;
}
}
当然,我们可以定义强类型的异常信息,并在方法上运用FaultContractAttribute来指定它,如下所示:
[DataContract]
publicclassMathFault
{
[DataMember]
publicstringoperation;
[DataMember]
publicstringdescription;
}
[ServiceContract]
publicclassCalculatorService
{
[FaultContract(typeof(MathFault))]
[OperationContract]
intDivide(inta,intb)
{
if(b==0)
{
MathFaultm=newMathFault();
m.operation=”/”;
m.description=”Divisionbyzero!”;
thrownewFaultException<MathFault>(m);
}
returna/b;
}
}
publicclassMathFault
{
[DataMember]
publicstringoperation;
[DataMember]
publicstringdescription;
}
[ServiceContract]
publicclassCalculatorService
{
[FaultContract(typeof(MathFault))]
[OperationContract]
intDivide(inta,intb)
{
if(b==0)
{
MathFaultm=newMathFault();
m.operation=”/”;
m.description=”Divisionbyzero!”;
thrownewFaultException<MathFault>(m);
}
returna/b;
}
}
注意:不能用XmlSerializer来序列化Fault相关的对象实例,即使在其上使用了XmlSerializerFormatAttribute属性。
为了调试目的,可以用ReturnUnknownExceptionsAsFaults配置项(配置文件)或是在服务上使用ServiceBehaviorAttribute属性来将所有异常作为Fault返回给客户端, 如下所示:
[ServiceContract]
[ServiceBehavior(ReturnUnknownExceptionsAsFaults=true)]
publicclassCalculatorService
{
[OperationContract]intDivide(inta,intb)
{
returna/b;//ThismaythrowtheDivideByZeroException.
}
}
[ServiceBehavior(ReturnUnknownExceptionsAsFaults=true)]
publicclassCalculatorService
{
[OperationContract]intDivide(inta,intb)
{
returna/b;//ThismaythrowtheDivideByZeroException.
}
}
本文地址:http://www.45fan.com/dnjc/70445.html