首页 新闻 会员 周边

ASP.NET Core Web API 返回 NoContent 的 json 反序列化问题

0
悬赏园豆:30 [已解决问题] 解决于 2023-07-25 20:12

今天在一个 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)

请问如何解决这个问题?

dudu的主页 dudu | 高人七级 | 园豆:30943
提问于:2023-07-25 17:40
< >
分享
最佳答案
0

通过下面的方法解决了,参考自 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);

dudu | 高人七级 |园豆:30943 | 2023-07-25 20:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册