Can I add an encoding header to a ContentResult?

Viewed 1892

For testing purpose I have implemented an endpoint on our ASP.NET Core Web Api, that returns the HTML content of a RSS news feed article.

[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
        };
    }
}

Though I am getting the HTML from the endpoint, the encoding is wrong as shown in below screenshot (the language is danish) - Sorry for the large image size. enter image description here

How can I add a header with the right encoding, before returning the ContentResult? Or can I go with a better suited return type? Since we are using ASP.NET Core Web Api, I can not use the HttpResponseMessage return type, from what I understand?

I hope someone can help me solve this. Thanks for your time so far.

EDIT: for some reason the encoding looks right, when I am hitting the endpoint from Postman. But not in Google Chrome.

1 Answers

return it like:

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