为何Results.Json对null做特殊处理?能否取消该逻辑?
关于ASP.NET Core中
Results.Json(null)的特殊行为疑问 以下是使用默认ASP.NET Core模板的最小复现示例:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Content-Type application/json, Body: true app.MapGet("/True", () => Results.Json(true)); // Content-Type application/json, Body: "string" app.MapGet("/String", () => Results.Json("string")); // Content-Type application/json, Body: {"someProperty":"someValue"} app.MapGet("/Object", () => Results.Json(new { SomeProperty = "someValue" })); // expected: Content-Type application/json, Body: null // actual: no Content-Type header, zero-length Body app.MapGet("/Null", () => Results.Json(null)); app.Run();
可以看到,Results.Json通常会返回Content-Type为application/json的响应,响应体为入参的JSON序列化结果,但传入null时是例外——此时无Content-Type头,响应体长度为0,这会导致客户端需额外处理该特殊情况,十分不便。
我知道可以通过自定义Results.Json的替代方法来规避此问题,但我想了解为何会出现这种情况。毕竟Results类的开发者特意为null实现了特殊处理逻辑,想必有合理的原因,但目前我尚未理解,且官方文档并未给出相关说明。
补充说明:
- 我清楚在第一个(
/True)和第三个(/Object)场景中无需使用Results.Json,但第二个场景必须使用,否则ASP.NET会返回Content-Type为text/plain的文本,这又会让客户端多一个特殊情况需要处理。 app.MapGet("/Null2", () => (object?)null);确实会返回预期结果(JSON编码的null)。
内容的提问来源于stack exchange,提问作者Heinzi
相关产品推荐
相关产品推荐

