从c#中的Azure函数返回HTML



我用c#写了一个返回html的Azure函数。当我从web浏览器发出请求时,它会以原始文本的形式显示完整的响应,而不是将其呈现为html。我想我需要在响应上设置ContentType标头。我试过这个答案,但似乎我需要一个nuget包…而且变得复杂了。

如何在Azure函数的响应上设置ContentType头?

这里有一种方法可以在Azure函数的响应上设置ContentType头,只使用System.Net命名空间(不需要添加任何引用或nuget包)。在本例中,要让浏览器呈现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;
}

第一个答案是。net Framework,如果你需要。net Core/6.0…

var html = "<html><head></head><body>Example Content</body></html>";
return new ContentResult()
{
Content = html,
ContentType = "text/html",
StatusCode = 200
};

最新更新