Search code examples
c#jsonxmlasp.net-mvcazure-functions

Azure Function not returning XML response


I am unable to return result object as XML. As I understand from the documentation, JsonResult formats the given object as JSON. However ObjectResult has content negotiation built in.

Despite both Accept and Content-Type headers set in the request to application/xml, the function always serialises the response object as 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);
}

I found the post Can Azure Functions return XML? which mentions that proper content negotiation is coming, so I assume that after 5 years in .Net Core 3.1 shall support this.

EDIT:

The code I was testing was run locally. Just noticed that the same code put into hosted Azure Function via "Develop in Portal" works perfectly and returns expected XML when Accept:application/xml is set in the request. Accept is sufficient condition, Content-Type does not need to be set.


Solution

  • Azure Function not returning XML response

    The easiest way is to rely on 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>
    

    You will get xml into string and then put that string into OKObjectResult

    for further information refer XML response