I write a C# HTTP Trigger Azure function to read a local XML file then return to caller. When I use the code:
req.HttpContext.Response.Headers.ContentType = "application/xml";
var content = await File.ReadAllTextAsync(templatePath);
return new OkObjectResult(content);
Azure function automatically add line below at the top of response:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
If I use "text/plain", the response return exactly local xml file.
So, how can I still use "application/xml" without the extra tag?
Thanks,
CodePudding user response:
Here what you can do is use
HttpResponseMessage
instead of theIActionResult
which will allow you to use theHttpResponseMessage
which helps in the creating the response with more control.Now we can use the
MediaTypeHeaderValue
to set the content type header without the wrapper.
Here I am reading a test file called “test.xml”
Complete Program:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.Net.Http.Headers;
namespace FunctionApp6
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
ILogger log)
{
string g = "C:\\Users\\test\\test.xml";
var xmlDataResult = await File.ReadAllTextAsync(g);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(xmlDataResult);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
return response;
}
}
}