自定义故障异常导致客户端上的wcf超时

时间:2011-03-31 14:09:13

标签: c# wcf faultexception

我遵循了关于如何创建自定义错误异常的相同示例(通过创建Exception类并在FaultContract中引用它),但是每当我尝试从服务器抛出异常时,我都会收到来自客户端和连接最接近。 奇怪的是,如果我使用默认的FaultException类从服务器抛出错误,那么客户端就会正确接收它。

这是一个片段:

[DataContract(Namespace = "http://MyApp.Common", Name = "WcfException")]
public class WcfException
{
    private string methodName;
    private string nameSpace;
    private string errorDescription;
    private string stackTrace;
    private System.Exception exCeption;

    public WcfException()
    {
        methodName = String.Empty;
        nameSpace = String.Empty;
        errorDescription = String.Empty;
        stackTrace = String.Empty;
        exCeption = null;
    }

    [DataMember]
    public System.Exception MethodException
    {
        get
        {
            return exCeption;
        }
        set
        {
            exCeption = value;
            errorDescription = exCeption.Message;
            stackTrace = exCeption.StackTrace;
        }
    } // and so on....

我像这样初始化服务器:

                Type serviceType = typeof(Proxy);
                Uri baseUri = new Uri(@"net.tcp://" + Environment.MachineName + ":8030/");
                NetTcpBinding Binding = new NetTcpBinding();
                serviceHost = new ServiceHost(serviceType, baseUri);

                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                serviceHost.Description.Behaviors.Add(behavior);

                ServiceDebugBehavior sdb = serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
                sdb.IncludeExceptionDetailInFaults = true;

                Binding.Name = "ConfigurationHttpChannel";
                Binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                Binding.Security.Mode = SecurityMode.None;
                Binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
                Binding.SendTimeout = new TimeSpan(0, 10, 0);
                Binding.OpenTimeout = new TimeSpan(0, 10, 0);
                Binding.CloseTimeout = new TimeSpan(0, 10, 0);
                Binding.MaxReceivedMessageSize = 65536;
                Binding.MaxBufferSize = 65536;
                Binding.MaxBufferPoolSize = 524288;
                Binding.TransferMode = TransferMode.Buffered;

                serviceHost.AddServiceEndpoint(typeof(IProxy), Binding, "MyApi");
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), Binding, "mex");

                serviceHost.Open();

我知道为什么我得到连接超时只有当我使用自定义异常时?

非常感谢。

1 个答案:

答案 0 :(得分:2)

您应该使用Fault Contract通过WCF发送异常。

http://msdn.microsoft.com/en-us/library/ms733721.aspx

您可以创建自定义错误例外

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