0

In .NET Core 2.2 returning NotFound() in a WebAPI controller like this:

[HttpGet]
public IActionResult DoSomething() {
  return NotFound(new IOException("Unable to locate specified resource."));
}

would respond with a 404 status code with JSON in the body of the response like this:

{
   "ClassName":"System.Exception",
   "Message":"Unable to locate specified resource.",
   "Data":null,
   "InnerException":null,
   "HelpURL":null,
   "StackTraceString":"Huge stack trace goes here...",
   "RemoteStackTraceString":null,
   "RemoteStackIndex":0,
   "ExceptionMethod":null,
   "HResult":-2146233088,
   "Source":"Namespace goes here...",
   "WatsonBuckets":null
}

However in .NET Core 5.0, the same exact code results in the following JSON:

{
   "TargetSite":null,
   "StackTrace":null,
   "Message":"Unable to locate specified resource.",
   "Data":{
      
   },
   "InnerException":null,
   "HelpLink":null,
   "Source":null,
   "HResult":-2146232800
}

Now apparently JSON serialization of an ObjectResult has changed between versions, but without throwing a real exception and manually serializing it with a separate error handler, is there a way to configure the serialization so NotFound() (or any other ObjectResult for that matter) will return the full exception object like it did previously?

Xorcist
  • 3,129
  • 3
  • 21
  • 47
  • Maybe you can create a customException which extends Exception. – Yiyi You Mar 19 '21 at 06:30
  • Apparently as of .NET Core 3.0 Newtonsoft.Json was replaced with System.Text.Json as the default JSON serializer. Which is why there is now a difference. Installing the [Microsoft.AspNetCore.Mvc.NewtonsoftJson](https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson) NuGet package will allow to override it with **services.AddControllers().AddNewtonsoftJson()**. – Xorcist Mar 19 '21 at 17:39
  • I would still like to know if there is a JsonSerializerOption that will allow exceptions to be fully serialized with System.Text.Json. – Xorcist Mar 19 '21 at 17:43

0 Answers0