简体   繁体   English

如何让 ASP.NET Core 返回 XML 结果?

[英]How to make ASP.NET Core return XML result?

[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")
   };
}

I called the action using Swagger and passed this parameter 'text value'我使用 Swagger 调用了该操作并传递了此参数“文本值”

Expected result should be an XML file like this: text value预期结果应该是这样的 XML 文件:文本值

Actual Result: strange json result without the passed value!实际结果:没有传递值的奇怪 json 结果! https://www.screencast.com/t/uzcEed7ojLe https://www.screencast.com/t/uzcEed7ojLe

I tried the following solutions but did not work:我尝试了以下解决方案,但没有奏效:

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

Try this solution试试这个解决方案

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

For ASP.NET core 2+, you need to configure XmlDataContractSerializerOutputFormatter , it could be found from Nuget :对于 ASP.NET core 2+,您需要配置XmlDataContractSerializerOutputFormatter ,它可以从Nuget找到:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(c =>
    {
        c.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
    });
}
  1. you are missing parameter in your attribute.您的属性中缺少参数。
  2. you can put produces attribute to declare what type of output format你可以把生产属性来声明什么类型的输出格式
  3. you can embrace IActionResult or directly return ContentResult.您可以包含 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 }; }

The above will give you以上会给你

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

you can refer to following link to understand more about IActionResult您可以参考以下链接以了解有关 IActionResult 的更多信息

What should be the return type of WEB API Action Method? WEB API Action Method 的返回类型应该是什么?

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

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