简体   繁体   English

从Web Api控制器返回XML

[英]Return XML from Web Api Controller

How to specify return xml from web api controller?In one browser data opens as XML,in other as JSON. 如何从Web api控制器指定返回xml?在一个浏览器中,数据以XML格式打开,在其他浏览器中以JSON格式打开。

Edit 编辑

Here is my action: 这是我的动作:

    [HttpGet]
    public IEnumerable<MagazineMeta> GetLastUploadPdfMeta(int count)
    {
       List<MagazineMeta> metas = _metaRepository
                 .GetAll()
                 .OrderBy(e => e.TimeAdd)
                 .Take(count)
                 .ToList();

       return metas;
    }

Add these 2 lines to the end of Application_Start in Global.asax.cs: 将这两行添加到Global.asax.cs的Application_Start的末尾:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());

EDIT: As @YishaiGalatzer pointed out, this is rather quick & dirty workaround to achieve what was originally asked in question. 编辑:正如@YishaiGalatzer指出的那样,这是一种快速而肮脏的解决方法,可以实现最初提出的问题。 To get desired response format include appropriate Accept header in request (in context of this question, "application/xml") 要获得所需的响应格式,请在请求中包含适当的Accept标头(在此问题的上下文中为“ application / xml”)

要使响应序列化,您还需要一行

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

And for others who want to enforce json instead, call this : 对于其他想要强制执行json的人,请调用以下命令:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM