我有一些使用dataContracts的WCF服务,我希望我希望通过自定义Dictionary<传递一个Exception。 string,object> Data属性中的数据,但是当我在抛出之前在此数组上添加任何数据时,我在自定义ServiceBehavior的ErrorHandler中收到以下错误:
Type 'System.Collections.ListDictionaryInternal'
带有数据合同名称 'ArrayOfKeyValueOfanyTypeanyType:HTTP://schemas.microsoft.com/2003/10/Serialization/Arrays' 不是预期的。不添加任何类型 静态地知道已知的名单 类型 - 例如,通过使用 KnownTypeAttribute属性或 将它们添加到已知类型列表中 传递给DataContractSerializer。
我是否总是需要创建一个带有注释为DataContract的Dictionary属性的自定义异常并抛出它?使用ErrorHandler的想法是避免在每个服务方法中处理异常,我还需要在方法中添加更多注释吗?我错过了什么?
供参考,这是我的FaultErrorHandler类:
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();
}
}
我的典型服务界面如下:
[ServiceContract(Name = "Service", Namespace = Schema.WebServiceStandard, SessionMode = SessionMode.Allowed)]
public interface IService
{
[OperationContract(Name = "GetSomething")]
[FaultContract(typeof(ValidationFault))]
LookupResult GetSomething();
}
答案 0 :(得分:4)
System.Exception实现了ISerializable,它由序列化程序以与Dictionary相同的方式处理 - 它可以被[de]序列化,但你需要告诉序列化器哪些类型将被[de]序列化。在异常情况下,您无法更改类声明,因此如果您希望使此方案有效,则需要在服务合同中添加已知类型(使用[ServiceKnownType])以用于该类用于Data属性(使用内部类型System.Collections.ListDictionaryInternal
)以及您将添加到数据字典的任何类型。下面的代码显示了如何做到这一点(虽然我真的建议不要这样做,你应该定义一些DTO类型来处理需要返回的信息,以防止必须处理Exception类的内部实现细节
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();
}
}
答案 1 :(得分:0)
您还必须为可能添加到[KnownType]
的任何非系统类型添加Dictionary<string , object>
属性。例如,如果您向字典添加MyType
,则需要添加[KnownType(typeof(MyType))]
。