【问题标题】:Return HTML from an Azure Function in c#从 C# 中的 Azure 函数返回 HTML
【发布时间】:2023-01-13 11:33:54
【问题描述】:
我用 c# 编写了一个 Azure 函数,它返回 html。当我从网络浏览器发出请求时,它会将完整的响应显示为原始文本,而不是将其呈现为 html。我想我需要在响应中设置 ContentType 标头。我尝试了this answer,但似乎我需要一个 nuget 包……而且变得复杂了。
如何在 Azure 函数的响应中设置 ContentType 标头?
【问题讨论】:
标签:
c#
html
azure-functions
content-type
【解决方案1】:
这是一种仅使用 System.Net 命名空间(不需要添加任何引用或 nuget 包)的 Azure Functions 响应设置 ContentType 标头的方法。在这种情况下,要让浏览器呈现 html,请设置 "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;
}