当前位置: 首页 > 编程语言 > C#

c#WCFCatchFaultExceptionofBaseType分享

时间:2023-04-10 21:45:30 C#

c#WCFCatchFaultExceptionofBaseType一直在寻找如何在c#中找到基本故障契约类型。我希望我所有的故障契约都继承自一个类,并在MVC控制器中有一个捕获(FaultExceptionfex)。DataContracts[DataContract]publicclassBaseClass1{}[DataContract]publicclassClass2:BaseClass1{}服务[ServiceContract]publicinterfaceIService1{[OperationContract][FaultContract(typeof(BaseClass1))][FaultContract(typeof(Class2))]//我需要这个吗?无效ThrowClass2();}publicclassService1:IService1{publicvoidThrowClass2(){thrownewFaultException(newClass2(),"Class2Reason");}}服务消费者FaultTestService.Service1Clientclient=null;尝试{client=newFaultTestService.Service1Client();client.ThrowAmpFaults("InvalidParameter",0);}catch(FaultExceptionfex){//不要像我预期的那样进入这里}catch(FaultExceptionfex){//其他可能的选项MessageFaultfault=fex.CreateMessageFault();varfe1=fault.GetDetail();//Thisthrowsaserializationexceptionitneeds}如果可以修复这些catch语句中的任何一个来执行我正在寻找的操作,请告诉我。该语法在C#中不起作用。请考虑下面的“解决方法”。try{thrownewFaultException(newDerivedClass2());}catch(FaultExceptionfex){boolhandled=false;输入fexType=fex.GetType();if(fexType.IsGenericType&&fexType.GetGenericTypeDefinition()==typeof(FaultException)){if(typeof(BaseClass1).IsAssignableFrom(fexType.GetGenericArguments()[0])){objectdetail=fexType.GetProperty("Detail").GetValue(fex,null);//在这里使用细节。handled=true;}}if(!handled)抛出;//不知道怎么处理。重新投掷。如果我们忽略Detail==null但构造的泛型类型匹配的异常情况,这可以简化。我还将使用C#动态关键字进一步简化它。try{thrownewFaultException(newDerivedClass2());}catch(FaultExceptionfex){boolhandled=false;输入fexType=fex.GetType();如果(fexType.IsGenericType&&fexType.GetGenericTypeDefinition()==typeof(FaultException)){objectdetail=((dynamic)fex).Detail;if(detailisBaseClass1)//子类也是如此!{//在这里使用细节。}}if(!handled)抛出;//不知道怎么处理。重新投掷。另一件要考虑的事情是你是否应该使用thrownewFaultException(newDerivedClass2())。此抛出允许您使用最初提供的代码。抱歉,没有办法做到这一点。FaultException和FaultException之间没有关系,因为T1可能是T2的子类。您的客户需要一个消息检查器。我们有一个类似的情况,服务器抛出各种异常,它们都以FaultException结束。以上就是C#学习教程:c#WCF捕获Base类型的故障异常分享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: