首页 > 解决方案 > 如何让 ASP.NET Core 返回 XML 结果?

问题描述

[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();

标签: c#xmlasp.net-coreasp.net-core-webapiwebapi

解决方案


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
    };
}

推荐阅读