代码之家  ›  专栏  ›  技术社区  ›  Martin Brandl

从Azure PowerShell函数提供HTML页面

  •  1
  • Martin Brandl  · 技术社区  · 7 年前

    我尝试从Azure提供HTML页面 PowerShell 作用我可以返回HTML,但我知道在哪里可以设置 内容类型为text/htm l以便浏览器解释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
    

    以下是浏览器中的响应:

    enter image description here

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

    1 回复  |  直到 4 年前
        1
  •  4
  •   Mikhail Shilkov    7 年前

    可以返回具有属性的响应对象 body ,则, headers ,则, status isRaw (可选):

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