views:

582

answers:

5

I want to return an anonymous type over WCF. Is this possible?

+1  A: 

No, it is not. You'll have to define your types ahead of time.

Randolpho
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??
Tamim Sadikali
See the answers of either Eugene Osovetsky or marc_s. Either route will help you. I'd say marc_s' answer is probably your best one for your problem.
Randolpho
+1  A: 

You can't return an anonymous type from any method, can you? So why would you be able to return it from WCF?

John Saunders
I don't understand this downvote - John is absolutely right, anonymous types cannot be returned from any .NET method, you can only ever use them **within** your current method. Why a downvote for a response that's 100% correct......
marc_s
+1  A: 

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

marc_s
Custom messages are probably the way to go for this one. +1
Randolpho
+1  A: 

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)]

Eugene Osovetsky
A: 

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.

Dave Ward