Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Serialization cannot write an object of type 'x'

I want to serialize a class as a response in MVC Web API using XmlFormatter but I get the following exception while creating the resonse:

MediaTypeFormatter formatter = Configuration.Formatters.XmlFormatter;
HttpResponseMessage resp = Request.CreateResponse<Model>(HttpStatusCode.OK, value: modelObject, formatter: formatter);

The exception:

The configured formatter 'System.Web.Http.Tracing.Tracers.XmlMediaTypeFormatterTracer' cannot write an object of type 'Model'.

What's wrong ?

like image 401
Mohsen Afshin Avatar asked Oct 12 '13 09:10

Mohsen Afshin


People also ask

What is XML serialization in c#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.

Which is the correct way of using XML deserialization?

The most common usage of XML serialization is when XML data is sent from the database server to the client. Implicit serialization is the preferred method in most cases because it is simpler to code, and sending XML data to the client allows the Db2 client to handle the XML data properly.

Which class should be used to serialize an object in XML format?

Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".


1 Answers

I digged the web for any clue of this error and found nothing after hours.

The answer was simple.

The Model class lacked a default constructor which caused a strange non-debug-able exception.

Further info: Why XML-Serializable class need a parameterless constructor

like image 95
Mohsen Afshin Avatar answered Sep 22 '22 07:09

Mohsen Afshin