ASP.NET Core:在 Json Response 中设置不同于 UTF-8 的字符集 [英] ASP.NET Core: Set charset different from UTF-8 in Json Response
问题描述
我在 ASP.NET Core 项目的控制器中有这个 get 请求
I have this get request in my controller in ASP.NET Core project
[HttpGet]
[Route("api/controller/getlastresult/{id}")]
public IActionResult GetLatestResultForController(string id)
{
Response.ContentType = "application/json";
var list = _dbAccessLayer.GetAllVoteResults();
var appropriateResults = list.Where(item => item.DeviceId.Equals(id) && item.Status == "Finished")
.OrderBy(item => item.TimeStarted);
if (appropriateResults.Any())
return Ok(Json(appropriateResults.Last().Result));
return BadRequest();
}
它工作正常,但在标题中有 Content-Type: application/json;charset=utf-8 如您所见:
It works fine, but in the headers there is Content-Type: application/json; charset=utf-8 as you can see here:
我只需要普通的 application/json,没有字符集 utf-8,所以我猜它会是 ASCII 字符集.原因是我将此请求与不喜欢 utf-8 编码的微控制器一起使用.
I need just regular application/json, without charset utf-8, so I guess it will be ASCII charset. Reason being that I use this request with microcontroller which does not like utf-8 encoding.
如何在我的 Get 请求的响应中设置chaset?谢谢
How do I set chaset in the response of my Get request? Thanks
推荐答案
对于删除字符集,你可以尝试像
For removing charset, you could try middleware like
app.Use(async (context, next) =>
{
context.Response.OnStarting((state) =>
{
if (context.Response.Headers.Count > 0 && context.Response.Headers.ContainsKey("Content-Type"))
{
var contentType = context.Response.Headers["Content-Type"].ToString();
if (contentType.StartsWith("application/json"))
{
context.Response.Headers.Remove("Content-Type");
context.Response.Headers.Append("Content-Type", "application/json");
}
}
return Task.FromResult(0);
}, null);
await next.Invoke();
});
这篇关于ASP.NET Core:在 Json Response 中设置不同于 UTF-8 的字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!