wcf 故障异常原因

Yak*_*kov 4 .net c# wcf exception faultexception

对于以下异常,异常窗口中未指定原因(->查看详细信息):

System.ServiceModel.FaultException 此错误的创建者未指定原因。我该如何更改它以显示原因?(我需要在那里显示 1234)

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

MyFaultException connEx = new MyFaultException();
connEx.Reason1 = "1234";
throw new FaultException<OrdersFaultException>(connEx);
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 5

虽然如果您希望将所有异常转发给调用者,I3arnon 答案很好,但如果您只想通过一组有限的已知故障,您可以创建故障契约,让调用者知道可能会出现一组特定的异常这样客户就可以准备好处理它们。这允许您传递潜在的预期异常,而无需转发您的软件可能向客户端抛出的所有异常。

下面是来自 MSDN 的一个简单示例,该示例显示了 WCF 服务捕获 aDivideByZeroException并将其转换为 aFaultException以传递给客户端。

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)