c# – wcf FaultException原因

对于以下异常,在异常窗口中未指定Reason( – >查看详细信息):

System.ServiceModel.FaultException The creator of this fault did not specify a Reason.
How can I change it to show the reason? (I need 1234 to be shown there)

public class MysFaultException
{
    public string Reason1
    {
        get;
        set;
    }
}

MyFaultException connEx = new MyFaultException();
connEx.Reason1 = "1234";
throw new FaultException<OrdersFaultException>(connEx);

解决方法

如果您希望将所有例外转发给呼叫者,I3arnon answer是好的,如果您只想要通过一组有限的已知故障,则可以创建 Fault Contracts,让调用者知道可能会遇到一组特定的异常,因此客户可以准备好处理它们.这允许您传递潜在的预期异常,而无需转发软件可能引发的所有异常.

以下是MSDN中的一个简单示例,它显示一个WCF服务捕获DivideByZeroException并将其转换为FaultException以传递给客户端.

[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    //... (Snip) ...

    [OperationContract]
    [FaultContract(typeof(MathFault))]
    int Divide(int n1,int n2);
}

[DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public class MathFault
{    
    private string operation;
    private string problemType;

    [DataMember]
    public string Operation
    {
        get { return operation; }
        set { operation = value; }
    }

    [DataMember]        
    public string ProblemType
    {
        get { return problemType; }
        set { problemType = value; }
    }
}

//Server side function
public int Divide(int n1,int n2)
{
    try
    {
        return n1 / n2;
    }
    catch (DivideByZeroException)
    {
        MathFault mf = new MathFault();
        mf.operation = "division";
        mf.problemType = "divide by zero";
        throw new FaultException<MathFault>(mf);
    }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...