Reputation: 1457
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.
Upvotes: 0
Views: 1941
Reputation: 1116
In an Azure Function Net7 isolated, you have to take care of setting the Content-Type of the request and then send as a string. This method that has been working in production.
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
{
var xml = @"<note>
<to>Customer</to>
<from>Sender</from>
<heading>Reminder</heading>
<body>Message</body>
</note>";
HttpResponseData? response;
response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Remove("Content-Type");
response.Headers.Add("Content-Type", "application/xml");
await response.WriteStringAsync(xml);
return response;
}
Upvotes: 1
Reputation: 2440
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
Upvotes: 3