如何在ASP.NET Core响应头中移除Content-Type的charset=utf-8后缀
问题原因
你在Action中提前给Response.ContentType赋值的操作会被后续的ASP.NET Core JSON输出格式化器覆盖,默认格式化器会自动追加charset=utf-8到Content-Type头中,所以你的设置没有生效。
解决方案
方案1:单接口快速适配(推荐,改动最小)
不要使用Ok()方法返回对象,直接构造ContentResult返回序列化后的JSON内容,显式指定ContentType即可:
[HttpPost] public IActionResult Post([FromBody] JObject jobject) { JObject changedObject = new JObject(); if (jobject.ContainsKey("name")) { changedObject.Add("id", "1"); changedObject.Add("name", jobject.GetValue("name")); changedObject.Add("employment", "private"); } return new ContentResult { Content = changedObject.ToString(Newtonsoft.Json.Formatting.None), ContentType = "application/json", StatusCode = StatusCodes.Status200OK }; }
如果代码报错,补充using Microsoft.AspNetCore.Http;命名空间引用即可。
方案2:全局配置所有JSON接口生效
如果需要项目所有返回JSON的接口都不带charset=utf-8后缀,在Program.cs(.NET 6+)中修改输出格式化器配置即可:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; builder.Services.AddControllers() .AddNewtonsoftJson() .Configure<MvcOptions>(options => { var jsonFormatter = options.OutputFormatters.OfType<NewtonsoftJsonOutputFormatter>().First(); // 移除带charset的默认media type,添加不带charset的版本 jsonFormatter.SupportedMediaTypes.Remove(MediaTypeHeaderValue.Parse("application/json; charset=utf-8")); jsonFormatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json")); });
如果是.NET 6之前版本,上述配置放到Startup.cs的ConfigureServices方法中即可。
方案3:中间件全局覆盖
也可以通过中间件在响应输出前统一修改Content-Type头,不需要修改现有接口逻辑:
// 放到Program.cs中间件管道的靠前位置,路由匹配之前 app.Use(async (context, next) => { await next.Invoke(); if (context.Response.ContentType?.StartsWith("application/json") == true) { context.Response.ContentType = "application/json"; } });
内容的提问来源于stack exchange,提问作者BaranwalG
相关产品推荐
相关产品推荐

