ASP.NET Core v3字符串响应默认返回text/plain,无偏好时如何优先返回JSON
配置ASP.NET Core字符串响应优先返回JSON格式的方案
核心原理:ASP.NET Core 3+ 版本调整了输出格式化器的默认排序,StringOutputFormatter(处理text/plain格式)优先级高于SystemTextJsonOutputFormatter(处理JSON格式),因此Accept头为*/*时会优先返回text/plain格式的字符串。调整格式化器排序即可恢复旧版本行为。
方案1:调整输出格式化器排序(推荐,无副作用)
该方案不会破坏text/plain格式的响应能力,仅调整通配符匹配时的优先级。
.NET 6+ 版本(Program.cs 配置)
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(options => { // 取出默认注册的字符串格式化器 var stringOutputFormatter = options.OutputFormatters .OfType<StringOutputFormatter>() .FirstOrDefault(); if (stringOutputFormatter != null) { // 先移除原有字符串格式化器 options.OutputFormatters.Remove(stringOutputFormatter); // 重新添加到格式化器列表末尾,优先级低于JSON格式化器 options.OutputFormatters.Add(stringOutputFormatter); } }); // 后续其他配置保持不变 var app = builder.Build(); // ... 中间件配置 app.Run();
.NET 5及更早版本(Startup.cs 配置)
public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { var stringOutputFormatter = options.OutputFormatters .OfType<StringOutputFormatter>() .FirstOrDefault(); if (stringOutputFormatter != null) { options.OutputFormatters.Remove(stringOutputFormatter); options.OutputFormatters.Add(stringOutputFormatter); } }); }
方案2:直接移除字符串格式化器(不推荐,仅适合完全不需要text/plain响应的场景)
如果你的服务完全不需要返回text/plain格式的响应,可以直接移除StringOutputFormatter,所有字符串响应都会走JSON序列化:
builder.Services.AddControllers(options => { var stringOutputFormatter = options.OutputFormatters .OfType<StringOutputFormatter>() .FirstOrDefault(); if (stringOutputFormatter != null) { options.OutputFormatters.Remove(stringOutputFormatter); } });
效果验证
配置完成后,当请求携带Accept: */*头时,返回响应的Content-Type为application/json,响应体为带双引号的"Hello, {name}",兼容旧客户端逻辑;当请求显式指定Accept: text/plain时,仍然可以正常返回text/plain格式的纯文本内容。
内容的提问来源于stack exchange,提问作者BB7788
相关产品推荐
相关产品推荐

