【问题标题】:MVC .net core : response type always json not xml with ICollectionMVC .net核心:响应类型总是json而不是带有ICollection的xml
【发布时间】:2017-07-24 13:09:50
【问题描述】:

我将此贡献用于返回 json 或 xml,具体取决于“Accept”标头。

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

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

我的对象

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; }
}

成功了!

但是当我向 Cartes 添加 ICollection 属性时,返回总是 JSON 格式!

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

UtilisationsCriteres 类:

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; }
}

控制器的返回类型是IActionResult。

知道为什么吗?

【问题讨论】:

    标签: c# json entity-framework asp.net-core asp.net-core-mvc


    【解决方案1】:

    我可以确认(奇怪的)行为。集合可以为空(或为空),内容从application/xml 更改为application/json

    使用接口而不是具体类型时,XML 序列化器似乎丢失了。也许你应该在https://github.com/aspnet/Mvc/issues 上创建一个新问题。

    解决方法是使用具体类。将ICollection&lt;UtilisationsCriteres&gt; 更改为System.Collections.ObjectModel.Collection&lt;UtilisationsCriteres&gt;List&lt;UtilisationsCriteres&gt; 似乎可行。

    【讨论】:

    • 谢谢它的工作!我可能会在 github 上添加一个问题 ;)
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2013-10-01
    • 2019-01-25
    • 2012-09-22
    相关资源
    最近更新 更多