【问题标题】:ASP.NET Web Api to return XML and get XMLASP.NET Web Api 返回 XML 并获取 XML
【发布时间】:2018-08-07 17:45:01
【问题描述】:

我有一个控制器,它以 json 格式返回数据。我希望该方法返回 XML 结构并将数据返回到 XML 结构。

我在 WebApiConfig 中添加了以下代码:

config.Routes.MapHttpRoute(
  name: "defaultapi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
  name: "VehicleApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");

Global.asax.cs

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

【问题讨论】:

标签: c# asp.net xml asp.net-mvc-4 asp.net-web-api


【解决方案1】:

要使 ASP.NET Web API 返回 XML,您无需进行任何代码更改。只需确保在 HTTP 请求中有这样的标头即可。

Accept: application/xml

有关内容协商的更多信息,请参阅this

【讨论】:

  • 在哪里添加接受:application/xml
  • 也让我知道我必须在哪里创建 XML 结构和受尊重的 xslt 文件,我在 ASP.NET MVC4 中做 web api
  • Accept: application/xml 应该添加到您的请求标头中。 Web API 将自动返回 XML。如果您只想返回一种格式strathweb.com/2013/06/…,这是一篇好文章
【解决方案2】:

我发现在使用 VBA MSXML2.XMLHTTP60 发出请求时,将请求标头设置为 Accept: application/xml 只会返回一个空白的 xml 对象。为了解决这个问题,我在我的 WebApiConfig.cs 文件的 Register 函数末尾添加了以下行:

config.Formatters.Add(new XmlMediaTypeFormatter());

然后我的对象按预期序列化。

【讨论】:

    【解决方案3】:

    确保您的返回类型是可序列化的。

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多