Search code examples
c#json.net-core-3.1asp.net-apicontroller

.NET CORE 3.1 Does ApiController decorator return json using System.Text.Json?


I am converting from .NET Core 2.2 to .NET Core 3.1 and I have been using the JsonApiDotNetCore class to return the object as OK in JSON format:

public class ClientsController : JsonApiController<Client>
{
    [AllowAnonymous]
    [HttpGet("/Route/Page")]
    public async Task<ActionResult> TestAsync()
    {
        // Do some stuff

        return Ok(someObject);

    }
}

I am looking at potentially moving away from JsonApiDotNetCore and using ControllerBase with the ApiController decorator. Does this decorator return the object that is formatted in JSON along with the HTTP status (i.e., OK = 200) using System.Text.Json? If not, is it possible to use that to return the object? I am wanting to do it this way because Microsoft has demonstrated that this new class is optimized for high performance.

public class ClientsController : ControllerBase
{
    [ApiController]
    [AllowAnonymous]
    [HttpGet("/Route/Page")]
    public async Task<ActionResult> TestAsync()
    {
        // Do some stuff

        return Ok(someObject);

    }
}

Solution

  • You will get JSON by default not because of the ApiController attribute but because it is a default behaviour when responding to the browser unless configured otherwise. See the documentation for details:

    Unlike typical API clients, web browsers supply Accept headers. Web browser specify many formats, including wildcards. By default, when the framework detects that the request is coming from a browser:

    • The Accept header is ignored.
    • The content is returned in JSON, unless otherwise configured.

    This provides a more consistent experience across browsers when consuming APIs.

    What does the ApiControler attribute is doing is well explained here and here. Basically it adds validation, attribute routing and other features. Again, see links for details.

    You can also check the source code to find all the references to the attribute as it is for instance in the ApiBehaviorApplicationModelProvider class - here in OnProvidersExecuting method.