JsonPatchDocument 可以使用属性吗

Can JsonPatchDocument use Attributes

我可以在我的对象上使用属性并仍然使用 JsonPatchDocument 吗?

目前,如果我有这个对象:

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

我只能在 post 请求和补丁请求中发送浮点数。

如果我添加属性:

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

我现在可以在 post 请求中只发送 1 到 100 之间的浮点数。不过在补丁中,即使我用 FloatTest = 1000 打补丁,ModelState 仍然有效。

有没有在 JasonPatchDocument 的 ApplyTo 函数中检查这个,或者有没有我错过的任何其他最佳实践?

使用TryValidateModel验证您的数据,参考以下代码:

[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);
        }
    }

结果: