我正在尝试创建一些自定义的 FaultException
。我已经制作了一个名为 CreateFault
的 DataContract
类。
[DataContract]
public class CreateFault
{
private string report;
public CreateFault(string message)
{
this.report = message;
}
[DataMember]
public string Message
{
get { return this.report; }
set { this.report = value; }
}
}
我接着在一个服务方法中抛出了异常。
在 IService1.cs
中
[OperationContract]
[FaultContract(typeof(CreateFault))]
void TestFaultException();
并且在 Service1.cs
中
public void TestFaultException()
{
throw new FaultException<CreateFault>(new CreateFault("CreateFault message"), "Message abt exception");
}
我在客户端捕获了FaultException
异常。
private void btnTest_Click(object sender, RoutedEventArgs e)
{
try
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.TestFaultException();
}
catch (FaultException<CreateFault> ex)
{
MessageBox.Show(ex.Detail.Message, "Success", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (FaultException ex)
{
MessageBox.Show(ex.Message, "Failure", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
}
}
现在问题来了。当我在Visual Studio 2010中创建一个WCF服务应用程序项目时,它按预期工作。错误被捕获在:
catch (FaultException<CreateFault> ex)
当我创建一个带有自定义 FaultExceptions
的 WCF Service Library 项目时,客户端无法识别我的自定义异常。相反地,它会在以下位置捕获错误:
catch (FaultException ex)
为什么它不能与WCF服务应用程序项目一起使用?
编辑: 这是我在调试过程中捕获异常时收到的信息。
catch (FaultException ex)
(在即时窗口中键入?ex)
{"关于异常的信息"}
[System.ServiceModel.FaultException<WpfApplication1.ServiceReference2.CreateFault>]: {"Message abt exception"}
base {System.ServiceModel.CommunicationException}: {"Message abt exception"}
Action: "http://tempuri.org/IService1/TestFaultExceptionCreateFaultFault"
Code: {System.ServiceModel.FaultCode}
Message: "Message abt exception"
Reason: {Message abt exception}
编辑2:
找到了问题所在。我有两个服务引用,它们都有CreateFault数据合同。当我运行程序时,它使用了错误的合同。
当我更改为
catch (FaultException<ServiceReference2.CreateFault> ex)
它起作用了
catch (FaultException ex)
它就可以工作了。 - Johan Björk