[英]JSON Patch Validation .Net Core
Has anyone found a good way to use data annotations to prevent specifc properties from being updated in a json patch doc.有没有人找到一种使用数据注释来防止特定属性在 json 补丁文档中更新的好方法。
Model:模型:
public class Entity
{
[DoNotAllowPatchUpdate]
public string Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Action { get; set; }
}
Logic:逻辑:
var patchDoc = new JsonPatchDocument<Entity>();
patchDoc.Replace(o => o.Name, "Foo");
//Prevent this from being applied
patchDoc.Replace(o => o.Id, "213");
patchDoc.ApplyTo(Entity);
The logic code is just an example of what the patch doc could look like coming from the client just generating in C# for quick testing purposes逻辑代码只是一个示例,说明补丁文档可能来自客户端,只是在 C# 中生成以进行快速测试
I wrote an extension method for JsonPatchDocument;我为 JsonPatchDocument 写了一个扩展方法; here's an abbreviated version:
这是一个缩写版本:
public static void Sanitize<T>(this Microsoft.AspNetCore.JsonPatch.JsonPatchDocument<T> document) where T : class
{
for (int i = document.Operations.Count - 1; i >= 0; i--)
{
string pathPropertyName = document.Operations[i].path.Split("/", StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
if (typeof(T).GetProperties().Where(p => p.IsDefined(typeof(DoNotPatchAttribute), true) && string.Equals(p.Name, pathPropertyName, StringComparison.CurrentCultureIgnoreCase)).Any())
{
// remove
document.Operations.RemoveAt(i);
//todo: log removal
}
}
}
Add a minimal attribute:添加一个最小属性:
[AttributeUsage(AttributeTargets.Property)]
public class DoNotPatchAttribute : Attribute
Apply the attribute to your class properties:将该属性应用于您的类属性:
public class SomeEntity
{
[DoNotPatch]
public int SomeNonModifiableProperty { get; set; }
public string SomeModifiableProperty { get; set; }
}
Then you can call it before applying the transformation:然后你可以在应用转换之前调用它:
patchData.Sanitize<SomeEntity>();
SomeEntity entity = new SomeEntity();
patchData.ApplyTo(entity);
You could create your own Attribute
.您可以创建自己的
Attribute
。 Something like :就像是 :
DoNotAllowPatchUpdate:Attribute{}
public class Entity
{
[DoNotAllowPatchUpdate]
public string Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Action { get; set; }
}
And then check for it like:然后检查它,如:
var notAllowedProperties = typeof(Entity).GetProperties()
.Where(x => Attribute.IsDefined(x, typeof(DoNotAllowPatchUpdate)))
.Select(x => x.Name).ToList();
now before you update them you can check notAllowedProperties
.现在在更新它们之前,您可以检查
notAllowedProperties
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.