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

3 回答 3

12

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
    };
}
于 2019-12-05T08:50:31.520 回答
1

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(c =>
    {
        c.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
    });
}
于 2019-12-05T08:05:43.233 回答
1
  1. 您的属性中缺少参数。
  2. 你可以把生产属性声明什么类型的输出格式
  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 的更多信息

WEB API Action Method 的返回类型应该是什么?

于 2019-12-05T08:53:09.570 回答