1

I am new to C# WebAPIs and I am trying to serialized XML on the return of data from API. Below is a model I have and the XML is not being serialized. The model is being serialized, however only the property names, not the XmlElement attributes on the properties. The JSON serialization works just fine, just not XML.

To return the data in the Controller Action, I am using Request.CreateResponse<Type>(code, data);

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Newtonsoft.Json;

[XmlType("Chapter")]
public class Chapter
{
    [XmlElement("ChapterNumber"), JsonProperty("ChapterNumber")]
    public Int32 number { get; set; }
    [XmlArray("Verses"), XmlArrayItem("Verse"), JsonProperty("Verses")]
    public List<Verse> verses { get; set; }
}

Any ideas?

1
  • This is happening with all models, not just the above. Commented Jun 25, 2018 at 23:01

1 Answer 1

1

You need to change the formatter

Possibility 1: Change input and output formatter

public void ConfigureServices(IServiceCollection services)  
{
    services.AddMvc()
        .AddXmlSerializerFormatters();
}

Posibility 2: Change only outputformatter

public void ConfigureServices(IServiceCollection services)  
{
    services.AddMvc(options =>
    {
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
}

Remark:

You need package Microsoft.AspNetCore.Mvc.Formatters.Xml, which should be in cluded in Microsof.AspNetCore.All metapackage

Maybe this link will help you for additional questions: https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.