ASP.NET Core如何移除API返回Content-Type中的charset参数?
解决ASP.NET Core JSON响应移除Content-Type中charset的最优方案
不需要复制所有逻辑,只需通过重写SystemTextJsonOutputFormatter的关键方法就能实现,步骤如下:
- 自定义一个继承自
SystemTextJsonOutputFormatter的格式化器,重写GetMediaTypeWithCharset方法,直接返回原始媒体类型(不附加charset):
public class NoCharsetSystemTextJsonOutputFormatter : SystemTextJsonOutputFormatter { public NoCharsetSystemTextJsonOutputFormatter(JsonSerializerOptions options) : base(options) { } protected override string GetMediaTypeWithCharset(string mediaType) { // 跳过添加charset的逻辑,直接返回原媒体类型 return mediaType; } }
- 在服务配置中替换默认的JSON格式化器:
builder.Services.AddControllers(options => { // 找到默认的SystemTextJsonOutputFormatter实例 var defaultJsonFormatter = options.OutputFormatters.OfType<SystemTextJsonOutputFormatter>().FirstOrDefault(); if (defaultJsonFormatter != null) { options.OutputFormatters.Remove(defaultJsonFormatter); // 添加自定义格式化器,复用原有序列化配置 options.OutputFormatters.Add(new NoCharsetSystemTextJsonOutputFormatter(defaultJsonFormatter.SerializerOptions)); } });
原理说明
SystemTextJsonOutputFormatter继承的TextOutputFormatter,会通过GetMediaTypeWithCharset方法自动为媒体类型追加charset=utf-8。重写这个方法后,直接返回原始的application/json,就能让响应头的Content-Type只保留application/json,完全复用原有JSON序列化的所有逻辑,无需重复实现。
内容的提问来源于stack exchange,提问作者musium
相关产品推荐
相关产品推荐

