Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only model property not serialized in Web API

As per the title, I'm seeing that my read-only model properties are not serialized in my Web API project. MVC 4 Web API, VS2010.

I've seen a multitude of posts like this stackoverflow question that state that the MVC 4 Web API beta did not support JSON serializing of read-only properties. But many additional references stated that the final release used JSON.NET instead of DataContractJsonSerializer so the issue should be resolved.

Has this issue been resolved or not? If not, am I forced to put in fake setters just to get serialization?


Correction, it does seem to work with JSON (sorry!), but XML exhibits the problem. So same question as before but in the context of XML serialization.

like image 318
tcarvin Avatar asked Jan 22 '13 16:01

tcarvin


1 Answers

The default JSON serializer is now Json.NET. So readonly property serialization should work without you having to do anything at all.

For XML, in 4.5 we added this flag to the DataContractSerializer:

http://msdn.microsoft.com/en-us/library/vstudio/system.runtime.serialization.datacontractserializersettings.serializereadonlytypes.aspx

You should be able to write something like this:

config.Formatters.XmlFormatter.SetSerializer(myType, new DataContractSerializer(myType, new DataContractSerializerSettings() { SerializeReadOnlyTypes = true });

Place this code in a function called by GlobalConfiguration.Configure in the Application_Start. By default this would be WebApiConfig.Register().

like image 89
Youssef Moussaoui Avatar answered Oct 31 '22 08:10

Youssef Moussaoui