c# - IncludeExceptionDetailInFaults 不像想象的那样表现

标签 c# .net wcf exception-handling

我有这个简单的测试项目只是为了测试 IncludeExceptionDetailInFaults 行为。

    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            throw new InvalidCastException("test");
            return string.Format("You entered: {0}", value);
        }
    }

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
    }

在服务的 app.config 中,我将其设置为 true

 <serviceDebug includeExceptionDetailInFaults="True" />

在客户端:

            try
            {
                using (var proxy = new ServiceReference1.Service1Client())
                    Console.WriteLine(proxy.GetData(5));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

这就是我认为的行为: 设置为 includeExceptionDetailInFaults=true 会将异常详细信息传播到客户端。但我总是收到 CommunicationObjectFaultException。

我确实尝试在契约(Contract)上使用 FaultContract(typeof(InvalidCastException)),但行为相同,只得到 CommunicationObjectFaultException。

让它工作的唯一方法是抛出 new FaultException(new InvalidCastException("test"));

但我认为使用 IncludeExceptionDetailInFaults=true 可以自动完成上述操作。

我错过了什么吗?

最佳答案

这是因为您已将服务客户端放在 using block 中。

WCF 客户端是您在 .NET 中的唯一位置 shouldn't use using ,因为它会掩盖“真正的”异常。

技术解释:Dispose 调用 Close,如果 channel 已经出现故障(即由于previous exception),随后将 that exception 放在堆栈的顶部。在清理一个ICommunicationObject时,为了避免屏蔽异常,你必须先检查State是否有错误,如果是则调用Abort 而不是 Close

关于c# - IncludeExceptionDetailInFaults 不像想象的那样表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2561420/

相关文章:

.net - WiX:同时注册 .NET COM 组件 x86 x64

c# - 有没有一种方法可以在不将数据转换为 DataTable 的情况下使用 SqlBulkCopy?

c# - MySQL asp.net 字符集不能正常工作

c# - 如何使用 wix 安装程序在自定义文件夹中安装应用程序,而不是 Program Files 文件夹

c# - MVC4 中的 ViewBag 可以为 null 吗?

.net - 什么时候 "Try"方法优于 "null"结果?

.net - SQL Server 共享内存通信协议(protocol)的使用

c# - 为什么在断点处继续太快会使我的服务器发送无效响应

c# - 使用 WCF 服务 - 找不到默认端点元素

c# - 以编程方式使用证书身份验证配置 WCF 服务客户端