0

This comment to an answer from John Saunders, a very high-rep member of Stack Overflow, says that returning an anonymous type from a web service is a bad practice.

Assuming I have the luxury of not caring about graceful degradation of my website in the face of users with Javascript disabled, why is it bad practice to have a service method, that exists only to be called via Ajax, return an anonymous object?

It seems like such a waste to whip up a concrete type, whose sole purpose is to hold my data for a few microseconds before asp.net serializes it into JSON.

Community
  • 1
  • 1
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Found this questions while trying to figure out why my ASMX tries to use XML serialization even if I forced JSON both on the ScriptMethod attribute and in the ajax call, and thus it won't serialize my anonymous object because it does not have a parameterless constructor. Have you found a solution to this? – Matteo Mosca Dec 13 '11 at 17:07
  • @MatteoMosca - that should work. There's probably a problem in your code - just post a new question and I'm sure someone can help. But yeah, returning should *work* fine, and be serialized into json without a problem - this question was about best practices. – Adam Rackis Dec 13 '11 at 17:14

1 Answers1

2

My comment was specific to SOAP web services. Consumers of SOAP web services are accustomed to working with strongly-typed data, so returning an object of anonymous type via an object return type will force them to parse the XML, which they aren't accustomed to doing.

However, for clients which do not expect (or understand) strongly-typed data, my comment does not apply. If they are already accustomed to parsing XML, or evaling JSON, then returning an anonymous object won't make that worse.

John Saunders
  • 160,644
  • 26
  • 247
  • 397