Search code examples
.netasp.net-coreasp.net-core-webapijson-patch

Can JsonPatchDocument use Attributes


Can I use Attributes on my objects and still use JsonPatchDocument?

Currently, if I have this object:

public class Test {
        public float FloatTest { get; set; }
}

I can only send in float, both in a post-request and in a patch-request.

If I add an attribute:

public class Test {
        [Range(1, 100)]
        public float FloatTest { get; set; }
}

I can now, in a post-request, only send in floats between 1 and 100. In patch though, ModelState stays valid even if I patch with FloatTest = 1000.

Is there anyway to check this in the ApplyTo-function in JasonPatchDocument, or is there any other best practice I've missed?


Solution

  • Use TryValidateModel to validate your data , refer to the below code :

    [HttpPatch]
        public IActionResult JsonPatchWithModelState([FromBody] JsonPatchDocument<Test> patchDoc)
        {
            if (patchDoc != null)
            {
                var test = new Test();
    
                // Apply book to ModelState
                patchDoc.ApplyTo(test, ModelState);
    
                // Use this method to validate your data
                TryValidateModel(test);
    
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                return new ObjectResult(test);
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
    

    Result : enter image description here