MVC.net core: response type is always json not xml with ICollection

I am using this input to return json or xml depending on the Accept header.

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting

services.AddMvc(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

      

My object

public partial class Cartes
{
    public Cartes()
    {

    }

    public string CartNumero { get; set; }
    public int? CartConsId { get; set; }
    public int CartLotcaId { get; set; }
    public int CartTypcaId { get; set; }
    public string CartCrc { get; set; }
    public DateTime? CartDateAttribution { get; set; }
    public DateTime? CartDateClotureCarte { get; set; }
    public DateTime? CartDateSaisie { get; set; }
}

      

It works!

But when I add the ICollection property to Cartes, the return is always in JSON!

public virtual ICollection<UtilisationsCriteres> UtilisationsCriteres { get; set; }

      

UtilisationsCriteres class:

public partial class UtilisationsCriteres
{
    public int UtcriConsId { get; set; }
    public int UtcriCrsupId { get; set; }
    public string UtcriValeur { get; set; }
    public int UtcriPartclieId { get; set; }
    public DateTime UtcriDateInsert { get; set; }
    public DateTime UtcriDateUpdate { get; set; }
    public string UtcriUserUpdate { get; set; }
}

      

The return type of the controller is IActionResult.

Any idea why?

+3


source to share


1 answer


I can confirm this (strange) behavior. The collection can be empty (or empty) and the content changes from application/xml

to application/json

.

The XML serializer seems to get lost when using an interface instead of a specific type. Maybe you need to post a new issue at https://github.com/aspnet/Mvc/issues .



The workaround is to use concrete classes. Change ICollection<UtilisationsCriteres>

to System.Collections.ObjectModel.Collection<UtilisationsCriteres>

or List<UtilisationsCriteres>

similar to work.

+1


source







All Articles