gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:36:12 24 4
gpt4 key购买 nike

我有这个简单的测试项目只是为了测试 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com