【问题标题】:Serving an HTML Page from Azure PowerShell Function从 Azure PowerShell 函数提供 HTML 页面
【发布时间】:2018-03-15 13:49:56
【问题描述】:

我尝试通过 Azure PowerShell 函数提供 HTML 页面。我能够返回 HTML,但我知道在哪里可以将 内容类型设置为 text/html,以便浏览器解释 HTML。

这里有一个example from Anythony Chu 你如何在 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;
}

但在 PowerShell 函数中,我只是使用 Out-File cmdlet 返回文件,并且没有设置内容类型的选项。这是一个 hello world 示例:

# 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

浏览器中的响应如下所示:

知道如何设置内容类型以便浏览器解释 HTML?

【问题讨论】:

  • 嗯,你可以用c#来设置内容类型吗?
  • @4c74356b41 我不明白你的问题。我想在 Azure PowerShell 函数中设置内容类型,而不是 C#。

标签: powershell azure azure-functions serverless faas


【解决方案1】:

您可以返回具有属性bodyheadersstatusisRaw(可选)的响应对象:

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

【讨论】:

  • 哇,这很容易:D。非常感谢你!你怎么知道的?
  • @mikhail 愿意分享源代码吗?
  • @4c74356b41 我只有this link 用于javascript
猜你喜欢
  • 1970-01-01
  • 2012-09-06
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多