Azure 函数未返回 XML 响应

Azure Function not returning XML response

我无法 return 结果 object 为 XML。据我从文档中了解到,JsonResult 将给定的 object 格式化为 JSON。但是 ObjectResult 内置了内容协商。

尽管 AcceptContent-Type headers 在请求中设置为 application/xml,函数总是将响应 object 序列化为 JSON.

[FunctionName("Function1")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
    ILogger log)
{
    ResponseMessage responseObject = new ResponseMessage
    {
        Code = "111",
        Message = "This response shall be XML formatted"
    };

    return new ObjectResult(responseObject);
}

我发现 post 提到适当的内容协商即将到来,所以我假设 .Net Core 3.1 5 年后应该支持这个。

编辑:

我测试的代码是 运行 本地的。刚刚注意到,通过“在门户中开发”放入托管 Azure 函数的相同代码工作完美,并且当在请求中设置 Accept:application/xml 时,预期 returns XML。 Accept是充分条件,Content-Type不需要设置。

A​​zure 函数未返回 XML 响应

最简单的方法是依赖Content Result

[FunctionName("ContentResultWithXmlInString")]
public static IActionResult Run4([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
{
    string xmlContent = File.ReadAllText("xmlcontent.xml");            
    return new ContentResult { Content = xmlContent, ContentType = "application/xml" };
}



  GET http://localhost:7071/api/ContentResultWithXmlInString HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:7071
    Accept: application/xml
    
    
    HTTP/1.1 200 OK
    Date: Fri, 25 May 2018 22:16:58 GMT
    Content-Type: application/xml
    Server: Kestrel
    Content-Length: 232
    
    <?xml version="1.0" encoding="utf-8" ?>
    <MyData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/HttpReturnXml">
      <Property1>Foo</Property1>
      <Property2>3</Property2>
    </MyData>

你会得到 xml 成字符串,然后把那个字符串放入 OKObjectResult

更多信息请参考XML response