I want to return an anonymous type over WCF. Is this possible?
You can't return an anonymous type from any method, can you? So why would you be able to return it from WCF?
You cannot use anonymous types, but maybe you are talking about WCF and untyped messages?
There is an option in WCF to just define a parameter of type Message
(and possibly a return value of the same type). This is just the raw message that goes to WCF (and comes back from it).
I can't find much good information out there - there's some documentation on MSDN, but the best I've seen so far is Kurt Claeys' blog post WCF : Untyped messages on WCF operations.
I would not recommend using this approach - it's a lot more grunt work to handle the message contents directly yourself and that's what WCF is trying to spare us from - but if you absolutely, positively have to tweak every bit of your message - this seems like the way to go.
Marc
OK, I understand. But then if I define a type - MyObj - for this purpose and mark its members IsRequired=false, how can I create+send across an instance of MyObj with only some of its members? Is this possible??
Take a look at [DataMember(EmitDefaultValue=false)]
You definitely can return anonymous types. This works, for example:
public object GetLatestPost()
{
XDocument feedXML = XDocument.Load("http://feeds.encosia.com/Encosia");
var posts = from feed in feedXML.Descendants("item")
select new
{
Title = feed.Element("title").Value,
Link = feed.Element("link").Value,
Description = feed.Element("description").Value
};
return posts.First();
}
If you call that method as an ASMX ScriptService's WebMethod, you'll get this JSON from it:
{"d":
{"Title":"Using an iPhone with the Visual Studio development server",
"Link":"http://feeds.encosia.com/~r/Encosia/~3/vQoxmC6lOYk/",
"Description":" Developing iPhone-optimized portions of an ASP.NET ..."}}
You can use a return type of IEnumerable to return a collection of anonymous types also.