今天在一个 ASP.NET Core 项目中遇到的问题,如果在 Action 中返回 NoContent
public async Task<IActionResult> GetBlogPosts(string blogApp)
{
// ...
if (blogSite.IsNullOrEmpty()
{
return NoContent();
}
// ...
}
在 System.Text.Json 反序列化时会报错
System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
---> System.Text.Json.JsonReaderException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
请问如何解决这个问题?
通过下面的方法解决了,参考自 https://github.com/dotnet/aspnetcore/issues/8847
Program.cs 中修改 HttpNoContentOutputFormatter 的设置
builder.Services.AddControllers(options =>
{
var noContentFormatter = options.OutputFormatters.OfType<HttpNoContentOutputFormatter>().FirstOrDefault();
if (noContentFormatter != null)
{
noContentFormatter.TreatNullValueAsNoContent = false;
}
});
Action 中将 return NoContent();
改为 return Ok(null);