Home > Software engineering >  Return HTML from an Azure Function in c#
Return HTML from an Azure Function in c#

Time:01-13

I wrote an Azure function in c# which returns html. When I make a request from a web browser, it displays the full response as raw text instead of rendering it as html. I think I need to set the ContentType header on the response. I tried this answer but it seems I'd need a nuget package... and got complicated.

How to set the ContentType header on a response from an Azure Function?

CodePudding user response:

Here's a way to set the ContentType header on a response from an Azure Function using only the System.Net namespace (which doesn't require adding any references or nuget packages). In this case, for html to be rendered by a browser, set "text/html".

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
    var html = "<html><head></head><body>Example Content</body></html>";
    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(html, Encoding.UTF8, "text/html");

    return response;
}

CodePudding user response:

The first answer is for .NET Framework, if you need .NET Core/6.0 ...

var html = "<html><head></head><body>Example Content</body></html>";

return new ContentResult()
{
    Content = html,
    ContentType = "text/html",
    StatusCode = 200
};
  • Related