【问题标题】:How to make ASP.NET Core return XML result?如何让 ASP.NET Core 返回 XML 结果?
【发布时间】:2020-03-30 02:46:06
【问题描述】:
[HttpGet]
[HttpPost]
public HttpResponseMessage GetXml(string value)
{
    var xml = $"<result><value>{value}</value></result>";
    return new HttpResponseMessage
   {
       Content = new StringContent(xml, Encoding.UTF8, "application/xml")
   };
}

我使用 Swagger 调用了该操作并传递了此参数“文本值”

预期的结果应该是这样的 XML 文件:文本值

实际结果: 没有传递值的奇怪 json 结果! https://www.screencast.com/t/uzcEed7ojLe

我尝试了以下解决方案,但没有奏效:

services.AddMvc().AddXmlDataContractSerializerFormatters();
services.AddMvc().AddXmlSerializerFormatters();

【问题讨论】:

  • 你是把这两个属性一起声明[HttpGet] [HttpPost] 吗?
  • ASP.NET Core 与旧的 Web API 是不同的野兽,它本身不能使用或理解 HttpResponseMessage。我还从 web API -> Core 进行了迁移,并且在它开始对我有意义之前必须忘记很多类似的东西。

标签: c# xml asp.net-core asp.net-core-webapi webapi


【解决方案1】:

试试这个解决方案

[HttpGet]
[HttpPost]
public ContentResult GetXml(string value)
{
    var xml = $"<result><value>{value}</value></result>";
    return new ContentResult
    {
        Content = xml,
        ContentType = "application/xml",
        StatusCode = 200
    };
}

【讨论】:

    【解决方案2】:
    1. 您的属性中缺少参数。
    2. 你可以把produces属性声明什么类型的输出格式
    3. 你可以拥抱 IActionResult 或者直接返回 ContentResult。

      [HttpGet("{value}")]
      [Produces("application/xml")]
      public IActionResult GetXml(string value)
      {
          var xml = $"<result><value>{value}</value></result>";
          //HttpResponseMessage response = new HttpResponseMessage();
          //response.Content = new StringContent(xml, Encoding.UTF8);
          //return response;
      
          return new ContentResult{
              ContentType = "application/xml",
              Content = xml,
              StatusCode = 200
          };
      }
      

    以上将给你

    <result>
        <value>hello</value>
    </result>
    

    您可以参考以下链接了解更多关于 IActionResult

    What should be the return type of WEB API Action Method?

    【讨论】:

      【解决方案3】:

      对于ASP.NET core 2+,需要配置XmlDataContractSerializerOutputFormatter,可以在Nuget找到:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 2018-07-21
        相关资源
        最近更新 更多