我在 ASP.NET Core 项目的控制器中有这个 get 请求
[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 正如你可以在这里看到的:
我只需要常规的 application/json,没有字符集 utf-8,所以我猜它将是 ASCII 字符集。原因是我将此请求与不喜欢 utf-8 编码的微控制器一起使用。
如何在 Get 请求的响应中设置字符集?
要删除字符集,您可以尝试像
这样的中间件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();
});