简体   繁体   中英

WCF REST: ReadAsDataContract using classes “WITHOUT” decoration attributes DataContract and DataMember

I have just done some tests and i have manged to get ReadAsDataContract working on the Response.Content method...

The thing that really is confusing is that i thought it shouldn't work yet! As my classes are NOT decorated with the DataContact or DataMember Attributes.

I am confused, reading the various tutorials around the web it seems that it is IMPORTANT to decorate your class (used for ReadAsDataContract) with DataContract and DataMember attributes..

BUT mine is not and i put a breakpoint on the line that calls ReadAsDataContract and sure enough i have a LIST returned with the correct details. Here is the line

List<Models.Question> questions = response.Content.ReadAsDataContract<List<Models.Question>>();

Models.Question is not decorated with the attributes. I share my model assembly with both my server and my client.

Can somebody tell me why it works when as far as i know you need to add the attributes on the class and members (which i have not)

I am using Visual Studio 2010 and .NET 4 - ermmm i seem to remember that these attributes are no longer required - is this true??

Really look forward to any help.

I hate it when things WORK and they SHOULD NOT :-) but of course I also hate when this DON'T WORK when they SHOULD :-)

THanks!

Can somebody tell me why it works when as far as i know you need to add the attributes on the class and members (which i have not)

It seems the "burden" of putting [DataContract] on data classes and [DataMember] on each member to be serialized was too much for the programmers worldwide - so Microsoft changed the behavior of the DataContractSerializer in .NET 3.5 SP1.

Since that time, the DCS will behave like the old XmlSerializer with a class that isn't decorated - it will happily serialize all public members and properties.

Problem with that is, of course: you loose all the additional control that the attributes give you, like defining an XML namespace for your data contracts, defining the order of the data members etc. - but it works without adding any attributes.

So this is a known and willingly introduced behavior. I still believe you ought to be explicit in your intent and mark your data classes with [DataContract] and your members with [DataMember] (which also gives you the ability to ignore one or several public members and not include them in serialization).

根据这一各类可序列化,而不仅仅是与DataContractAttribute的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM