c# - wcf FaultException 原因

标签 c# .net wcf exception faultexception

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

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);
    }
}

关于c# - wcf FaultException 原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954915/

相关文章:

javascript - 如何缩小和合并注释掉的 css 文件

c# - EF在急切加载和延迟加载方面的区别?

c# - 如何向 RESTful WCF 服务传递和使用 JSON 参数?

c# - WCF - NetMsmqBinding 与 NetTcpBinding

c# - 如何覆盖 DataGridRow 模板中的 AlternatingRowBackground?

c# - 如何优雅地处理 fxCop 警告 "Catch specific Exception than type System.Exception"?

c# - 如何将带有错误规范(无效用户名或无效密码)的 HttpResponseException 返回给前端?

c# - 查找/消除重复字符串的方法

.net - svcutil排除/重复使用引用的程序集

c# - 具有给定枚举的所有元素的枚举,并在 LINQ 中中断其他元素