Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net core mvc - .NET 5.0 MVC return Json is throwing a JSON Parser error

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);
}

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.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

To meet your requirement,you need add NewtonSoft support:

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

2.Update Startup.ConfigureServices to call AddNewtonsoftJson.

services.AddControllers()
    .AddNewtonsoftJson();

Reference:

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-5.0&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...