Close

Return Xml from Azure Function

To return XML from a function, you can use ContentResult instead of ActionResult. Relevant statement: return new ContentResult { Content = retval.InnerXml, ContentType = “application/xml” };

using System.Threading.Tasks;
using System.Xml;

namespace Function.RelatieHelper
{
    public static class VictimMessage
    {
        [FunctionName("CreateVictimSiblingMessage")]
        public static async Task<IActionResult> CreateVictimSiblingMessage(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string msg = await new StreamReader(req.Body).ReadToEndAsync();
            string victimId = GetHeaderValue(req, "victimId");


            if (msg == null)
            {
                return (ActionResult)new BadRequestObjectResult("XmlMessage ism null");
            }

            if (String.IsNullOrEmpty(victimId))
            {
                return (ActionResult)new BadRequestObjectResult("VictimId is null");
            }

            XmlDocument retval = new XmlDocument();

            using (var stream = new MemoryStream())
            {
                var writer = new StreamWriter(stream);
                writer.Write(msg);
                writer.Flush();
                stream.Position = 0;

                retval.Load(stream);

                retval.SelectSingleNode("//*[local-name() = 'relationid']").InnerText = victimId;
                retval.SelectSingleNode("//*[local-name() = 'relation_extern_id']").InnerText = victimId;
                
            }

            return new ContentResult { Content = retval.InnerXml, ContentType = "application/xml" };
                            
        }

        private static string GetHeaderValue(HttpRequest req, string headerName)
        {

            StringValues headerValues;
            string headerValue = null;

            if (req.Headers.TryGetValue(headerName, out headerValues))
            {
                headerValue = headerValues[0];
            }

            return headerValue;

        }
    }
}