Search code examples
asp.net-mvcasp.net-web-apixml-serialization

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 response:

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?


Solution

  • 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