我正在尝试在 WCF 服务中实现 FaultException。我参考了各种文章。然而,似乎 FaultExceptions 从未在客户端被捕获。我写过这样的代码,
服务合约 -
[ServiceContract]
public interface IService2
{
[OperationContract]
[FaultContract(typeof(MyException))]
[DebuggerStepThrough]
MyException GetData(int value);
}
[DataContract]
public class MyException
{
[DataMember]
public bool Result { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public Exception MyInnerException { get; set; }
[DataMember]
public string ClientMessage { get; set; }
}
服务实施——
public class Service1 : IService2
{
public MyException GetData(int value)
{
MyException mx = new MyException();
try
{
double a = 44;
if (value == 0)
{
throw new DivideByZeroException();
}
double res = a / value;
mx.ClientMessage = "Everything is well";
mx.Result = true;
return mx;
}
catch (DivideByZeroException dvex)
{
mx.Result = true;
mx.ClientMessage = "Divide by zero";
mx.MyInnerException = dvex;
mx.ErrorMessage = dvex.StackTrace;
throw new FaultException<MyException>(mx, dvex.ToString());
}
}
}
客户端(aspx.cs 页面)-
try
{
FaultContractsDemo.ServiceReference1.Service2Client o = new ServiceReference1.Service2Client();
MyException data = o.GetData(0);
if (data.Result)
lblMessage.Text = "All is well";
}
catch (FaultException<MyException> ex)
{
lblMessage.Text = ex.Detail.ClientMessage;
}
服务层抛出异常,但客户端从未收到任何异常。我收到未处理的异常,例如,
基础连接已关闭:连接意外关闭。