[DataContract]
public class DataPacket
{
[DataMember]
public List<DataEvent> DataEvents { get; set; }
}
[DataContract]
[KNownType(typeof(IntEvent))]
[KNownType(typeof(BoolEvent))]
public class DataEvent
{
[DataMember]
public ulong Id { get; set; }
[DataMember]
public DateTime Timestamp { get; set; }
public override string ToString()
{
return string.Format("DataEvent: {0},{1}",Id,Timestamp);
}
}
[DataContract]
public class IntEvent : DataEvent
{
[DataMember]
public int Value { get; set; }
public override string ToString()
{
return string.Format("IntEvent: {0},{1},{2}",Timestamp,Value);
}
}
[DataContract]
public class BoolEvent : DataEvent
{
[DataMember]
public bool Value { get; set; }
public override string ToString()
{
return string.Format("BoolEvent: {0},Value);
}
}
我的服务将在单个数据包中发送/接收子类型事件(IntEvent,BoolEvent等),如下所示:
[ServiceContract]
public interface IDataService
{
[OperationContract]
[WebGet(UriTemplate = "GetExampleDataEvents")]
DataPacket GetExampleDataEvents();
[OperationContract]
[WebInvoke(UriTemplate = "SubmitDataEvents",RequestFormat = Webmessageformat.Json)]
void SubmitDataEvents(DataPacket dataPacket);
}
public class DataService : IDataService
{
public DataPacket GetExampleDataEvents()
{
return new DataPacket {
DataEvents = new List<DataEvent>
{
new IntEvent { Id = 12345,Timestamp = DateTime.Now,Value = 5 },new BoolEvent { Id = 45678,Value = true }
}
};
}
public void SubmitDataEvents(DataPacket dataPacket)
{
int i = dataPacket.DataEvents.Count; //dataPacket contains 2 events,but both are type DataEvent instead of IntEvent and BoolEvent
IntEvent intEvent = dataPacket.DataEvents[0] as IntEvent;
Console.WriteLine(intEvent.Value); //null pointer as intEvent is null since the cast Failed
}
}
当我将数据包提交到SubmitDataEvents方法时,我收到DataEvent类型,并尝试将它们转换为基本类型(仅用于测试目的)导致InvalidCastException.我的包是:
POST http://localhost:4965/DataService.svc/SubmitDataEvents HTTP/1.1
User-Agent: fiddler
Host: localhost:4965
Content-Type: text/json
Content-Length: 340
{
"DataEvents": [{
"__type": "IntEvent:#WcfTest.Data","Id": 12345,"Timestamp": "\/Date(1324905383689+0000)\/","Value": 5
},{
"__type": "BoolEvent:#WcfTest.Data","Id": 45678,"Value": true
}]
}
对长篇文章抱歉,但是我可以做些什么来保护每个对象的基本类型?我以为添加类型提示到JSON和KNownType属性到DataEvent将允许我保留类型 – 但它似乎不起作用.
编辑:如果我将请求发送到XML格式的SubmitDataEvents(使用Content-Type:text / xml而不是text / json),则List< DataEvent> DataEvents确实包含子类型而不是超类型.一旦我将请求设置为text / json并发送上述数据包,那么我只得到超类型,我不能将它们转换为子类型.我的XML请求体是:
<ArrayOfDataEvent xmlns="http://schemas.datacontract.org/2004/07/WcfTest.Data">
<DataEvent i:type="IntEvent" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Id>12345</Id>
<Timestamp>1999-05-31T11:20:00</Timestamp>
<Value>5</Value>
</DataEvent>
<DataEvent i:type="BoolEvent" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Id>56789</Id>
<Timestamp>1999-05-31T11:20:00</Timestamp>
<Value>true</Value>
</DataEvent>
</ArrayOfDataEvent>
编辑2:更新服务描述之后Pavel的评论.在fiddler2中发送JSON数据包时仍然无效.我只是得到一个包含DataEvent而不是IntEvent和BoolEvent的List.
编辑3:正如Pavel所建议的,这是System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.ToString()的输出.看起来对我来说
<root type="object">
<DataEvents type="array">
<item type="object">
<__type type="string">IntEvent:#WcfTest.Data</__type>
<Id type="number">12345</Id>
<Timestamp type="string">/Date(1324905383689+0000)/</Timestamp>
<Value type="number">5</Value>
</item>
<item type="object">
<__type type="string">BoolEvent:#WcfTest.Data</__type>
<Id type="number">45678</Id>
<Timestamp type="string">/Date(1324905383689+0000)/</Timestamp>
<Value type="boolean">true</Value>
</item>
</DataEvents>
</root>
跟踪数据包的反序列化时,我在跟踪中收到以下消息:
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Verbose">
<TraceIdentifier>http://msdn.microsoft.com/en-GB/library/System.Runtime.Serialization.ElementIgnored.aspx</TraceIdentifier>
<Description>An unrecognized element was encountered in the XML during deserialization which was ignored.</Description>
<AppDomain>1c7ccc3b-4-129695001952729398</AppDomain>
<ExtendedData xmlns="http://schemas.microsoft.com/2006/08/ServiceModel/StringTraceRecord">
<Element>:__type</Element>
</ExtendedData>
</TraceRecord>
该消息重复4次(以__type为单元,两次为Value).看起来类型提示信息被忽略,那么Value元素将被忽略,因为数据包反序列化为DataEvent而不是IntEvent / BoolEvent.
解决方法
您的数据包不正确正确的是:
POST http://localhost:47440/Service1.svc/SubmitDataEvents HTTP/1.1
User-Agent: fiddler
Host: localhost:47440
Content-Length: 211
Content-Type: text/json
[
{
"__type":"IntEvent:#WcfTest.Data","Id":12345,"Timestamp":"\/Date(1324757832735+0700)\/","Value":5
},{
"__type":"BoolEvent:#WcfTest.Data","Id":45678,"Timestamp":"\/Date(1324757832736+0700)\/","Value":true
}
]
注意Content-Type头.
我已经尝试了你的代码,它的工作完美(我已经删除了Console.WriteLine并在调试器中测试).所有的类层次结构都很好,所有对象都可以被转换为它们的类型.有用.
UPDATE
您发布的JSON可以使用以下代码:
[DataContract]
public class SomeClass
{
[DataMember]
public List<DataEvent> dataEvents { get; set; }
}
...
[ServiceContract]
public interface IDataService
{
...
[OperationContract]
[WebInvoke(UriTemplate = "SubmitDataEvents")]
void SubmitDataEvents(SomeClass parameter);
}
请注意,另一个高级节点被添加到对象树.
再次,它继承良好.
如果问题仍然存在,请发布您用于调用服务的代码以及获取的异常详细信息.
更新2
多么奇怪…它在我的机器上工作.
我使用.NET 4和VS2010与Win7 x64上的最新更新.
我接受您的服务合同,实施和数据合同.我在Cassini的网络应用程序中托管他们.我有以下web.config:
<configuration>
<connectionStrings>
<!-- excluded for brevity -->
</connectionStrings>
<system.web>
<!-- excluded for brevity -->
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication1.DataService">
<endpoint address="ws" binding="wsHttpBinding" contract="WebApplication1.IDataService"/>
<endpoint address="" behaviorConfiguration="WebBehavior"
binding="webHttpBinding"
contract="WebApplication1.IDataService">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
</configuration>
现在我通过fiddler2进行以下POST(重要的是:我已经将派生类型的命名空间重命名为符合我的情况):
POST http://localhost:47440/Service1.svc/SubmitDataEvents HTTP/1.1
User-Agent: fiddler
Content-Type: text/json
Host: localhost:47440
Content-Length: 336
{
"DataEvents": [{
"__type": "IntEvent:#WebApplication1",{
"__type": "BoolEvent:#WebApplication1","Value": true
}]
}
然后我在服务实现中有以下代码:
public void SubmitDataEvents(DataPacket parameter)
{
foreach (DataEvent dataEvent in parameter.DataEvents)
{
var message = dataEvent.ToString();
Debug.WriteLine(message);
}
}
请注意,调试器将项目详细信息显示为DataEvents,但字符串表示和细节中的第一个项目清楚地显示所有子类型已经反序列化:
并且调试输出包含以下内容后我打了方法:
IntEvent: 12345,26.12.2011 20:16:23,5 BoolEvent: 45678,True
我也尝试在IIS(在Win7下)运行它,一切都很好.
我通过从__type字段名称中删除一个下划线,在损坏数据包之后,只有反序列化的基类型.如果我修改__type的值,则在反序列化期间,调用将崩溃,它不会触发服务.
这是你可以尝试的:
>确保没有任何调试消息,异常等(检查调试输出).
>创建一个新的干净的Web应用程序解决方案,粘贴所需的代码并测试它是否在那里工作.如果是,那么您的原始项目必须有一些奇怪的配置设置.
>在调试器中,在Watch窗口中分析System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.ToString().它将包含从您的JSON翻译的XML消息.检查是否正确.
>检查您是否有任何等待更新的.NET.
>尝试tracing WCF.虽然似乎没有发出任何警告的错误__type字段名称的消息,可能会发生,它会显示一些提示您的问题的原因.
我的请求消息
像这里似乎是这个问题的轨迹:当你有__type作为元素,我有它作为属性.假设您的WCF程序集在JSON到XML翻译中有错误
<root type="object">
<DataEvents type="array">
<item type="object" __type="IntEvent:#WebApplication1">
<Id type="number">12345</Id>
<Timestamp type="string">/Date(1324905383689+0000)/</Timestamp>
<Value type="number">5</Value>
</item>
<item type="object" __type="BoolEvent:#WebApplication1">
<Id type="number">45678</Id>
<Timestamp type="string">/Date(1324905383689+0000)/</Timestamp>
<Value type="boolean">true</Value>
</item>
</DataEvents>
</root>
我找到了处理__type的地方.这里是:
// from System.Runtime.Serialization.Json.XmlJsonReader,System.Runtime.Serialization,Version=4.0.0.0
void ReadServerTypeAttribute(bool consumedobjectChar)
{
int offset;
int offsetMax;
int correction = consumedobjectChar ? -1 : 0;
byte[] buffer = BufferReader.GetBuffer(9 + correction,out offset,out offsetMax);
if (offset + 9 + correction <= offsetMax)
{
if (buffer[offset + correction + 1] == (byte) '\"' &&
buffer[offset + correction + 2] == (byte) '_' &&
buffer[offset + correction + 3] == (byte) '_' &&
buffer[offset + correction + 4] == (byte) 't' &&
buffer[offset + correction + 5] == (byte) 'y' &&
buffer[offset + correction + 6] == (byte) 'p' &&
buffer[offset + correction + 7] == (byte) 'e' &&
buffer[offset + correction + 8] == (byte) '\"')
{
// It's attribute!
XmlAttributeNode attribute = AddAttribute();
// the rest is omitted for brevity
}
}
}
我试图找到使用属性来确定反序列化类型的地方,但是没有运气.
希望这可以帮助.