.NET 5.0 MVC返回Json抛出JSON分析器错误 [英] .NET 5.0 MVC return Json is throwing a JSON Parser error

查看:45
本文介绍了.NET 5.0 MVC返回Json抛出JSON分析器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个要从.NET Core 2.2迁移到.NET 5.0的应用程序.除了一件事情,一切都按预期进行.当遇到异常时,我们将其捕获并将其添加到将以JSON返回的错误消息列表中.这是一个非常简化的示例:

We have an application that we are migrating from .NET Core 2.2 to .NET 5.0. Everything is working as expected except one thing. When we encounter an exception we catch it and add it to a list of error messages that will be return as JSON. Here is a very simplified example:

public JsonResult TestingJson()
{
    Response response = new Response();

    try
    {
        throw new TimeoutException();
    }
    catch (Exception ex)
    {
        response.ErrorMessages.Add(new ErrorMessage {
            Exception = ex,
            Text = ex.Message,
            CreatedDate = DateTime.Now
        });
    }

    return Json(response);
}

返回Json(response)给我:"SyntaxError:JSON输入意外结束".如果我不添加"Exception = ex",当我构建响应对象时,一切正常.似乎无法将异常转换为JSON.我的问题是,在Core 2.2中一切正常.我在迁移过程中错过了什么吗?我知道这是一个模糊的问题,但我希望有人遇到了这种情况,并且可能知道我所缺少的内容.

The return Json(response) is giving me: "SyntaxError: Unexpected end of JSON input". If I don't add "Exception = ex" as I am building out my response object everything works fine. It seems as if it cannot convert the exception to JSON. My issue is, it all worked fine in Core 2.2. Did I miss something in my migration? I know this is a vague question but I am hoping someone has run into something like this and might know what I am missing.

谢谢

推荐答案

asp.net core 2.2默认情况下使用 Newtonsoft.Json .作为改进ASP.NET Core共享框架的工作的一部分,从asp.net core 3.0开始, Newtonsoft.Json (Json.NET)已从ASP.NET Core共享框架中删除.

asp.net core 2.2 use Newtonsoft.Json by default.As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json (Json.NET) has been removed from the ASP.NET Core shared framework since asp.net core 3.0.

要满足您的要求,您需要添加NewtonSoft支持:

To meet your requirement,you need add NewtonSoft support:

1.安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 软件包版本5.0.0.

1.Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package version 5.0.0.

2.Update Startup.ConfigureServices以调用 AddNewtonsoftJson .

2.Update Startup.ConfigureServices to call AddNewtonsoftJson.

services.AddControllers()
    .AddNewtonsoftJson();

参考:

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆