开发者

Why can I not use the KnownType attribute in my WCF class?

I am using WCF to retrieve a collection of objects. The objects are all of type ProcedureText but may be of child classes SuspensionText or ResumptionText, both of which inherit from ProcedureText.

public class ProcedureText { }
public class SuspensionText : ProcedureText { }
public class ResumptionText : ProcedureText { }

My OperationContract specifies a method returning an array of ProcedureText objects:

[OperationContract]
[WebGet(UriTemplate = "procedureTexts")]
ProcedureText[] GetProcedureTexts();

This works if I cast all my objects to ProcedureText but I want to keep the distinction of using the sub-types. I had hoped to use the KnownType attribute to do this and had expected to be able to do it by adding it to my ProcedureText class:

[S开发者_Go百科ystem.Runtime.Serialization.KnownType(typeof(SuspensionTextDto))]
[System.Runtime.Serialization.KnownType(typeof(ResumptionTextDto))]
public class ProcedureText { }

This doesn't work because the compiler cannot resolve System.Runtime.Serialization.KnownType. I know from the document that the attribute is part of .NET Framework 4, but I am using .NET Framework 4 and that is the Target Frameweork for my project.

Why do I need to set to be able to use the attribute?


The relevant DLL containing that type is not added by default. You need to add a reference to:

System.Runtime.Serialization

The usage is described in the documentation:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.knowntypeattribute.aspx

Basically it is so that the serializer recognises the type. Your service contract returns an array of the base class, however the types in that array could be more derived. If the serializer is not told this, the serialization will fail I think.


Without explicitly adding the reference to the project, I was able to use " I was able to use "using System.Runtime.Serialization" in my code but when I used attributes like "KnownType" or "DataMember" the compiler gave an error.

I was able to overcome this issue by explicitly adding the reference. Go to "Add References" in your project and search for "System.Runtime.Serialization" under Assemblies and add the dll to the project.

Works in .net 4.5 and 4.5.1 so I assume this will work in 4.0 as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜