Skip to content

NewtonsoftJsonPatchInputFormatter not working for non generic JsonPatchDocument with System.Text.Json #60446

Open
@buslm

Description

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When using System.Text.Json, patches to dynamic objects using the non-generic type JsonPatchDocument are not processed correctly.

The CanRead method of the NewtonsoftJsonPatchInputFormatter class does not allow non-generic types.

With this behavior, patch requests are not handled correctly and the InputFormatter falls back to the default of System.Text.Json, which cannot deserialize this request into a suitable object.

public override bool CanRead(InputFormatterContext context)
{
    ArgumentNullException.ThrowIfNull(context);

    var modelType = context.ModelType;
    if (!typeof(IJsonPatchDocument).IsAssignableFrom(modelType) ||
        !modelType.IsGenericType)
    {
        return false;
    }

    return base.CanRead(context);
}

Expected Behavior

Perhaps the type should be treated explicitly

public override bool CanRead(InputFormatterContext context)
{
    ArgumentNullException.ThrowIfNull(context);

    var modelType = context.ModelType;
    if (!typeof(IJsonPatchDocument).IsAssignableFrom(modelType) ||
        !(modelType.IsGenericType && modelType.Equals(typeof(JsonPatchDocument))))
    {
        return false;
    }

    return base.CanRead(context);
}

Steps To Reproduce

  1. Setup a project like described
  2. Create Endpoint for dynamic objects
  3. Send Request to Endpoint

Exceptions (if any)

No response

.NET Version

.NET 8.0

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Needs: Attention 👋This issue needs the attention of a contributor, typically because the OP has provided an update.area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions