繁体   English   中英

JSON 补丁验证 .Net Core

[英]JSON Patch Validation .Net Core

有没有人找到一种使用数据注释来防止特定属性在 json 补丁文档中更新的好方法。

模型:

 public class Entity
 {
    [DoNotAllowPatchUpdate]
    public string Id     { get; set; }

    public string Name   { get; set; }

    public string Status { get; set; }

    public string Action { get; set; }
 }

逻辑:

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

逻辑代码只是一个示例,说明补丁文档可能来自客户端,只是在 C# 中生成以进行快速测试

我为 JsonPatchDocument 写了一个扩展方法; 这是一个缩写版本:

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
        }
    }
}

添加一个最小属性:

[AttributeUsage(AttributeTargets.Property)]
public class DoNotPatchAttribute : Attribute

将该属性应用于您的类属性:

public class SomeEntity
{
    [DoNotPatch]
    public int SomeNonModifiableProperty { get; set; }
    public string SomeModifiableProperty { get; set; }
}

然后你可以在应用转换之前调用它:

patchData.Sanitize<SomeEntity>();

SomeEntity entity = new SomeEntity();

patchData.ApplyTo(entity);

您可以创建自己的Attribute 就像是 :

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

然后检查它,如:

    var notAllowedProperties = typeof(Entity).GetProperties()
      .Where(x => Attribute.IsDefined(x, typeof(DoNotAllowPatchUpdate)))
      .Select(x => x.Name).ToList();

现在在更新它们之前,您可以检查notAllowedProperties

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM