代码之家  ›  专栏  ›  技术社区  ›  Lloyd

无法在ASP中序列化为XML。净核心2

  •  5
  • Lloyd  · 技术社区  · 8 年前

    我现在对基本的ASP很困惑。NET Core 2 API项目和内容协商并返回JSON以外的内容。

    我以前在1.1项目中做过这项工作,但在2项目中没有。我基本上希望根据请求类型以JSON或XML的形式返回某些内容。

    作为该要求的一部分,我设置了XML格式化程序,如下所示:

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

    我也可以使用 AddXmlSerializerFormatters() 但相同的差异(并尝试过)。这是我在无数的例子中看到的,也是我以前做过的。

    我有一个控制器和一个动作,基本上看起来像:

    [Route("api/[controller]")]
    public class DefaultController : Controller
    {
        [HttpGet]
        [Route("")]
        public IActionResult Index()
        {
            return Ok(new
            {
                success = true
            });
        }
    }
    

    现在,当我跑的时候,我从邮递员那里得到了这个:

    {"success": true}
    

    因此它对JSON有效(或至少默认)。

    如果我请求使用标题 Accept: application/xml 相反,我现在得到一个HTTP错误406。

    如果我起飞 options.ReturnHttpNotAcceptable = true; ,它将返回JSON。

    我错过了什么?我坐在那里挠头。据我所知,我已经注册了一个可接受的内容格式化程序。

    3 回复  |  直到 8 年前
        1
  •  9
  •   Camilo Terevinto Chase R Lewis    8 年前

    您看到的问题是,匿名类型无法序列化为XML,因此格式化程序会失败并返回到JSON格式化程序。

    解决方案:需要返回XML时使用类。

        2
  •  1
  •   zxczzx    7 年前

    There is already open issue for that .

    作为一种解决方法,请尝试将此选项添加到Mvc:

    options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "text/xml");
    

    具有[FormatFilter]属性

        3
  •  0
  •   uzay95    6 年前

    正如@So曾经说过的那样,匿名类型不能序列化为XML。以下是我的示例:

    [AllowAnonymous]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class ProducesResponseFormatController : ControllerBase {
        [HttpGet]
        [Produces("application/xml")]
        public IActionResult Get() {
            // this worked well
            return Ok(new Model.appsettings.TokenSettings()); 
    
            // this didn't
            return Ok(new { A = new { B = "b inside a", C = "C inside A" }, D = "E" }); 
        }
    }
    
    推荐文章