powershellazureazure-functionsserverlessfaas

Serving an HTML Page from Azure PowerShell Function


I try to serve a HTML Page from an Azure PowerShell Function. I am able to return the HTML but I have clue where I can set the content type to text/html in order that the Browser interprets the HTML.

Here is an example from Anythony Chu how you can do it in C#:

public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(@"d:\home\site\wwwroot\ShoppingList\index.html", FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

But in a PowerShell function I just return the file using the Out-File cmdlet and don't have the option to set the content type. Here a hello world example:

# POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$name = $requestBody.name

# GET method: each querystring parameter is its own variable
if ($req_query_name) 
{
    $name = $req_query_name 
}

$html = @'
<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>
'@

Out-File -Encoding Ascii -FilePath $res -inputObject $html

Here is how the response looks like in the Browser:

enter image description here

Any idea how I can set the content type so that the Browser interprets the HTML?


Solution

  • You may return a Response object with properties body, headers, status and isRaw (optional):

    $result = [string]::Format('{{ "status": 200, "body": "{0}", "headers": {{ 
    "content-type": "text/html" }} }}', $html)
    Out-File -Encoding Ascii $res -inputObject $result;