如何从ASP.NET MVC 5 6控制器操作返回XML [英] How to return XML from an ASP.NET 5 MVC 6 controller action

查看:956
本文介绍了如何从ASP.NET MVC 5 6控制器操作返回XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从一个控制器动作返回XML?甚至当我添加标题接受:应用/ XML 它返回一个JSON对象

How can I return XML from a controller action? Even when I add the header Accept: application/xml it returns a JSON object.

的WebAPI控制器支持这一点。我有什么做的,使其在MVC 6工作?

WebApi controllers in MVC 5 supported this. What do I have to do to make it work in MVC 6?

推荐答案

微软删除了XML格式,让ASP.NET MVC 6只返回默认JSON。如果您想再次添加对XML的支持,请拨打 AddXmlSerializerFormatters services.AddMvc() Startup.ConfigureServices()方法:

Microsoft removed the XML formatter, so that ASP.NET MVC 6 returns only JSON by default. If you want to add support for XML again, call AddXmlSerializerFormatters after services.AddMvc() in your Startup.ConfigureServices() method:

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

要使用它,你必须添加Microsoft.AspNet.Mvc.Formatters.Xml:6.0.0-RC1决赛的依赖(在 project.json 依赖)。

To use it, you have to add "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final" as dependency (in the project.json under dependencies).

做同样的事情的一个稍微繁琐的方法是直接添加的xml格式的OutputFormatters系列:

A slightly more tedious way of doing the same thing would be to add the Xml formatter directly to the OutputFormatters collection:

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

XmlSerializerOutputFormatter 是命名空间中的 Microsoft.AspNet.Mvc.Formatters

这篇关于如何从ASP.NET MVC 5 6控制器操作返回XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆