我可以向 ContentResult 添加编码标头吗?

问题描述 投票:0回答:2

出于测试目的,我在 ASP.NET Core Web Api 上实现了一个端点,它返回 RSS 新闻提要文章的 HTML 内容。

[HttpGet]
[Route("/api/[controller]/NewsItemHtml/{id}")]
public IActionResult GetNewsItemHtml(int id)
{
    if (string.IsNullOrEmpty(id.ToString())) return new StatusCodeResult((int)HttpStatusCode.BadRequest);
    using (NewsBLL bll = new NewsBLL(_dbContext))
    {
        NewsItem newsItem = bll.GetNewsItem(id);
        if (newsItem == null) return new StatusCodeResult((int)HttpStatusCode.NotFound);

        return new ContentResult
        {
            ContentType = "text/html",
            StatusCode = (int)HttpStatusCode.OK,
            Content = newsItem.Description
        };
    }
}

虽然我从端点获取 HTML,但编码是错误的,如下面的屏幕截图所示(语言是丹麦语) - 抱歉图像尺寸较大。

如何在返回 ContentResult 之前添加具有正确编码的标头?或者我可以选择更适合的返回类型吗?由于我们使用的是 ASP.NET Core Web Api,因此我无法使用 HttpResponseMessage 返回类型,据我了解?

我希望有人能帮我解决这个问题。感谢您到目前为止的宝贵时间。

编辑:由于某种原因,当我从邮差到达端点时,编码看起来是正确的。但在 Google Chrome 中不行。

c# html .net-core character-encoding asp.net-core-webapi
2个回答
4
投票

像这样返回:

return Content("<html><body><div><h3>sometext</h3></div></body></html>", "text/html", System.Text.Encoding.UTF8);

0
投票

在 Asp.Net Core 中使用 ContentResult 执行此操作的另一种方法是在 ContentType 中包含字符集,以便将其与 Content-Type-header:

一起发送
return new ContentResult
{
    ContentType = "text/html; charset=utf-8",
    StatusCode = (int)HttpStatusCode.OK,
    Content = newsItem.Description
};
© www.soinside.com 2019 - 2024. All rights reserved.