C# MVC.NET核心web API XML或JSON

C# MVC.NET核心web API XML或JSON,c#,json,xml,asp.net-mvc,.net-core,C#,Json,Xml,Asp.net Mvc,.net Core,我想创建一个以XML或JSON形式返回数据的web应用程序,我该如何做呢 模型: namespace ReturningJSONandXML.Models { public class SomeImportantInformation { public int ID { get; set; } public string Information { get; set; } } } 控制员: namespace ReturningJSONa

我想创建一个以XML或JSON形式返回数据的web应用程序,我该如何做呢

模型:

namespace ReturningJSONandXML.Models
{
    public class SomeImportantInformation
    {
        public int ID { get; set; }
        public string Information { get; set; }
    }
}
控制员:

namespace ReturningJSONandXML.Controllers
{
    public class GetInfoController : Controller
    {
        // GET: /<controller>/
        public List<SomeImportantInformation> Get()
        {
            List<SomeImportantInformation> ImportantInfo = new List<SomeImportantInformation>();
            ImportantInfo.Add(new SomeImportantInformation { ID = 0, Information = "Awesome info" });
            ImportantInfo.Add(new SomeImportantInformation { ID = 1, Information = "Some other interesting info" });
            return ImportantInfo;
        }
    }
}
namespace ReturningJSONandXML.Controllers
{
公共类GetInfoController:Controller
{
//获取://
公共列表Get()
{
List ImportantInfo=新列表();
Add(newsomeimportantinfo{ID=0,Information=“Awesome info”});
Add(newsomeimportantinfo{ID=1,Information=“someotherinterest info”});
返回重要信息;
}
}
}
我想返回一个XML和JSON文件


我应该在这里使用什么样的最佳实践?

框架会自动为您处理这些问题,这样您就不必重新发明轮子了。答案引述如下

但更简单的是:除非指定
Accept
头,否则API将把响应序列化为JSON。例如,如果指定
'application/xml'
,它将返回xml

正如MSDN所说:

内容协商(简称conneg)发生在客户端 指定一个。这个 ASP.NET核心MVC使用的默认格式是JSON。内容协商 由
ObjectResult
实现。它还内置在状态代码中 从helper方法返回的特定操作结果 全部基于
ObjectResult
)。还可以返回模型类型(a) 类(定义为数据传输类型)和框架 将为您自动将其包装在
ObjectResult

仅当出现
Accept
标题时,才会进行内容协商 在请求中。当请求包含accept标头时 框架将在中的accept标头中枚举媒体类型 并将尝试找到可以生成 以accept标头指定的格式之一响应。万一 找不到能够满足客户端请求的格式化程序 框架将尝试找到第一个可以生成 响应(除非开发人员已在
mvcopions
返回406(不可接受)。如果请求 指定XML,但尚未配置XML格式化程序,则 将使用JSON格式化程序。更一般地说,如果没有使用格式化程序 配置为可以提供请求的格式,然后 使用可以格式化对象的格式化程序。如果没有给出标题, 可以处理要返回的对象的第一个格式化程序将是 用于序列化响应。在这种情况下,没有任何 正在进行协商-服务器正在确定协商的格式 将使用


从MSDN--and.

以及core 2中,您需要专门向mvc服务器添加选项,以启用xml输入/输出:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.InputFormatters.Add(new XmlSerializerInputFormatter());
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });
    }
然后将Accept标头更改为:

应用程序/xml 或
application/json在ASP.NETCore2.0中,您可以使用更短的语法

Startup
class'
ConfigureServices
方法中,您应该具有:

services
    .AddMvc()
    .AddXmlSerializerFormatters();
接受复杂对象的控制器如下所示:

[Route("api/Documents")]
public class DocumentsController : Controller
{
    [Route("SendDocument")]
    [HttpPost]
    public ActionResult SendDocument([FromBody]DocumentDto document)
    {
        return Ok();
    }
}
这是它将接受的XML:

<document>
    <id>123456</id>
    <content>This is document that I posted...</content>
    <author>Michał Białecki</author>
    <links>
        <link>2345</link>
        <link>5678</link>
    </links>
</document>
就这样!将同一文档以XML或JSON格式发送到
api/documents/SendDocument
端点即可。请记住在请求中包含正确的
内容类型
标题

有关更多内容,您可以在我的博客上阅读全文:

api将把响应转换为您在请求头上放置的任何内容。。。application/json或application/xml如果您使用的是mvc6(ASP.NET核心),框架将自动协商内容(返回@NicoRiff所说的适当内容类型)。更多信息。
{
    id: "1234",
    content: "This is document that I posted...",
    author: "Michał Białecki",
    links: {
        link: ["1234", "5678"]
    }
}