Skip to main content
 首页 » 编程设计

c#之使用包含方法的自定义 FaultException 类型

2024年02月20日15sky-heaven

在我的 WCF 服务上,我有几个自定义故障类型。一个名为 BaseFault 的抽象类型及其两个实现,分别称为 TypeOneFault 和 TypeTwoFault

我是这样在服务端抛出异常的

public string ThisMethodHasFault(string eType) 
{ 
    if (eType.Contains("One")) 
    { 
        TypeOneFault one = new TypeOneFault("TypeOneFault thrown"); 
        throw new FaultException<TypeOneFault>(one, new FaultReason(new FaultReasonText("Fault reason here"))); 
    } 
    else 
    { 
        TypeTwoFault two = new TypeTwoFault("TypeTwoFault thrown"); 
        throw new FaultException<TypeTwoFault>(two, new FaultReason(new FaultReasonText("Fault reason here"))); 
    } 
 
    return ""; 
} 

我的Service界面是这样的

[OperationContract] 
[FaultContract(typeof(TypeOneFault ))] 
[FaultContract(typeof(TypeTwoFault ))] 
string ThisMethodHasFault(string eType); 

在客户端,我有一个测试 winform 应用程序,我可以像这样捕获它

   MyServiceClient client = new MyServiceClient(); 
 
   try 
    { 
        client.ThisMethodHasFault(""); //get value from user 
 
    } 
    catch (FaultException<TypeOneFault>  ox) 
    { 
         TypeOneFault oneEx = ox.Detail; 
         oneEx.{property} ... 
 
    }    
    catch (FaultException<TypeTwoFault>  tx) 
    { 
         TypeTwoFault twoEx = tx.Detail; 
         twoEx.{property} ... 
    }     

问题:

在上面的方法中,我只获得自定义故障类的属性,而不是我在其中定义的方法。该方法在我在子类 TypeOne 和 TypeTwo 中实现的基本抽象类中定义为抽象。有办法得到方法吗?

请您参考如下方法:

方法不序列化。只有数据。