What is the difference between binding JsonDocument and a JsonElement in .NET 5?

Viewed 765

Task:
I am going to provide endpoint for 3rd party push notifications utilizing asp.net core 5.0. Push notifications have different types and schemas. These notifications need to put in mysql database in json column, and read few values to create an internal event and put that in a queue. So I want to bind request body to a "json object" from which I can read values, and after that save in database as is.

Choice issue:
Asp.net core 5.0 uses System.Text.Json. System.Text.Json provides type JsonDocument, which according to documentation should to be disposed, and JsonElement. Binding mechanism allow to bind request body to both JsonDocument and JsonElement:

[HttpPost]
public async Task<ActionResult> ProcessNotificationAsync(
    [FromBody] JsonDocument notification,
    [FromServices] IProcessNotificationCommand processCommand)
{
    await processCommand.ProcessAsync(notification);
    return NoContent();
}
[HttpPost]
public async Task<ActionResult> ProcessNotificationAsync(
    [FromBody] JsonElement notification,
    [FromServices] IProcessNotificationCommand processCommand)
{
    await processCommand.ProcessAsync(notification);
    return NoContent();
}

Which approach is safe to use, bind to JsonDocument or bind to JsonElement?
If I use binding to JsonDocument would binding mechanism dispose JsonDocument, when request handled? Or it required to me to code that?

[HttpPost]
public async Task<ActionResult> ProcessNotificationAsync(
    [FromBody] JsonDocument notification,
    [FromServices] IProcessNotificationCommand processCommand)
{
    using (notification)
    {
        await processCommand.ProcessAsync(notification);
    }
    return NoContent();
}
0 Answers
Related