I’m new to ASP.NET Web API.
I saw examples of how you can get and return POCOs in RESTful web application.
I wonder how in real world application you can pass only some of the properties of your POCO (for security and/or message size reasons).
I found that I can use the ‘[ScriptIgnore]’ attribute, but I’m looking for a way to customize which properties to pass according to the requesting controller, for example.
Does there is a nice, out of the box way, to do so?
Thanks
Probably the easiest is to decorate your POCO with
System.Runtime.Serialization.DataContractAttributeand the members you want to include withSystem.Runtime.Serialization.DataMemberAttributei.e.In this case only
Property1will be serialized. It;s worth noting, that bothXmlMediaTypeFormatterandJsonMediaTypeFormatterwill respectDataContractso you don’t need any XML/JSON specific attrbiutes.Now, this will work in simpler solutions, for a real, well rounded approach you’d probably need to resort to DTOs instead of exposing your Models to the client.
You could use
Automapperfor that, and project Models to DTOs – you have a good introductory article here http://www.mono-software.com/blog/post/Mono/120/Using-AutoMapper-to-handle-DTOs/. Also, with Automapper you can have different types of DTOs created from the same base Model, which, I understand, is something you are interested in.