1

I have some WCF services using dataContracts and i wanted to I was hoping to pass a Exception with custom Dictionary< string , object > data in the Data property, but when i add any data on this array before throwing i get the following error in the ErrorHandler of my custom ServiceBehavior:

Type 'System.Collections.ListDictionaryInternal'

with data contract name 'ArrayOfKeyValueOfanyTypeanyType:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

Do i invariably need to create a custom exception with a Dictionary property annotated as a DataContract and throw that? the idea of using the ErrorHandler is avoiding to handle exceptions in each service method, do i still need to add further annotations to the methods? what i am missing?

for reference, this is my FaultErrorHandler class:

public class FaultErrorHandler : BehaviorExtensionElement, IErrorHandler, IServiceBehavior
    {
        public bool HandleError(Exception error)
        {
            if (!Logger.IsLoggingEnabled()) return true;
            var logEntry = new LogEntry
            {
                EventId = 100,
                Severity = TraceEventType.Error,
                Priority = 1,
                Title = "WCF Failure",
                Message = string.Format("Error occurred: {0}", error)
            };
            logEntry.Categories.Add("MiddleTier");

            Logger.Write(logEntry);
            return true;
        }

        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            var faultException = new FaultException<Exception>( error, new FaultReason(string.Format("System error occurred, exception: {0}", error)));
            var faultMessage = faultException.CreateMessageFault();
            fault = Message.CreateMessage(version, faultMessage, Schema.WebServiceStandard);
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
            {
                chanDisp.ErrorHandlers.Add(this);
            };
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
        }

        public override Type BehaviorType
        {
            get { return typeof(FaultErrorHandler); }
        }

        protected override object CreateBehavior()
        {
            return new FaultErrorHandler();
        }
    }

my typical service interface looks like:

[ServiceContract(Name = "Service", Namespace = Schema.WebServiceStandard, SessionMode = SessionMode.Allowed)]
    public interface IService 
    {

        [OperationContract(Name = "GetSomething")]
        [FaultContract(typeof(ValidationFault))]
        LookupResult GetSomething();
    }
4

2 回答 2

4

System.Exception 实现 ISerializable,它由序列化程序以与 Dictionary 相同的方式处理 - 它可以被 [de] 序列化,但您需要告诉序列化程序哪些类型将被 [de] 序列化。在异常的情况下,您不能更改类声明,因此如果您想让这个场景工作,您需要在服务合同中添加已知类型(使用 [ServiceKnownType]),这两个类将是用于 Data 属性(使用内部类型System.Collections.ListDictionaryInternal)以及您将添加到数据字典中的任何类型。下面的代码显示了如何做到这一点(尽管我真的建议不要这样做,但您应该定义一些 DTO 类型来处理需要返回的信息,

public class StackOverflow_6552443
{
    [DataContract]
    [KnownType("GetKnownTypes")]
    public class MyDCWithException
    {
        [DataMember]
        public Exception myException;

        public static MyDCWithException GetInstance()
        {
            MyDCWithException result = new MyDCWithException();
            result.myException = new ArgumentException("Invalid value");
            result.myException.Data["someData"] = new Dictionary<string, object>
            {
                { "One", 1 },
                { "Two", 2 },
                { "Three", 3 },
            };
            return result;
        }

        public static Type[] GetKnownTypes()
        {
            List<Type> result = new List<Type>();
            result.Add(typeof(ArgumentException));
            result.Add(typeof(Dictionary<string, object>));
            result.Add(typeof(IDictionary).Assembly.GetType("System.Collections.ListDictionaryInternal"));
            return result.ToArray();
        }
    }
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        MyDCWithException GetDCWithException();
    }
    public class Service : ITest
    {
        public MyDCWithException GetDCWithException()
        {
            return MyDCWithException.GetInstance();
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();

        Console.WriteLine(proxy.GetDCWithException());

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
于 2011-07-01T22:54:55.990 回答
0

您还必须为[KnownType]可能添加到Dictionary<string , object>. 因此,例如,如果您将 a 添加MyType到字典中,那么您将需要添加[KnownType(typeof(MyType))].

于 2011-07-05T01:59:08.867 回答