Search code examples
asp.net-web-apijson.netasp.net-core-6.0output-formatting

Can I redefine output formatter for one controller method in Net Core 6?


All my method in Backend API working fine and return correct JSON by the same way

Return OK(obj)
Return Unauthorized()
Return StatusCode(StatusCodes.Status500InternalServerError, obj)

But in one method I want return raw JSON without standard formatter. I have correct JArray as result of method, for example lake this

correct JSON

However, when I try to return this JSON as result of controller I receive this result

wrong result

Any experiments like transform my JArray to object and return IActionResult with object was failed because JArray can be different and has complex and sophisticated structure. Therefore I want to redefine output formatter for this method. But don't understand how it's possible for exactly one method.


Solution

  • JArray is the class in Newtonsoft.Json. As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json has been removed from the ASP.NET Core shared framework for .NET 6.

    You need add the Newtonsoft.Json support according to your requirement.

    Follow the steps:

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

    2.Update Program.cs to call AddNewtonsoftJson.

    builder.Services.AddControllersWithViews().AddNewtonsoftJson();