Reputation: 435
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.
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.
Upvotes: 2
Views: 3506
Reputation: 4207
Another way of doing this with ContentResult in Asp.Net Core is to include charset in ContentType so that it will be sent with Content-Type-header:
return new ContentResult
{
ContentType = "text/html; charset=utf-8",
StatusCode = (int)HttpStatusCode.OK,
Content = newsItem.Description
};
Upvotes: 2
Reputation: 386
return it like:
return Content("<html><body><div><h3>sometext</h3></div></body></html>", "text/html", System.Text.Encoding.UTF8);
Upvotes: 4