首页 > 解决方案 > 如何在模型验证中验证非法字段

问题描述

我有一个接受 PersonDto 的 .NET Core 2.2 web-api,它正在使用模型验证进行验证,但它不检查非法字段。它只检查匹配字段是否有效。

我想确保提供的 JSON 仅包含我的 Dto(类)中的字段。

public class PersonDto
  {
    public string firstname { get; set; }
    public string lastname { get; set; }
  }

我的控制器看起来像这样简化:

public async  Task<ActionResult<Person>> Post([FromBody] PersonDto personDto)
{
    // do things
}

我发送的字段不正确(名称在我的 dto 中不存在)并且 ModelState 有效。

{
  "name": "Diego"
}

我希望模型验证会抱怨“名称”字段不存在。

如何检查非法字段?

标签: asp.net-coreasp.net-core-webapi

解决方案


您可以使用ActionFilterandReflection将请求正文内容与模型字段进行比较。如果有意外的字段,手动添加模型错误,ModelState.IsValid就会为假。

1.创建一个动作过滤器

public class CompareFieldsActionFilter : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext context)
    { 
        //get all fields name
        var listOfFieldNames = typeof(PersonDto).GetProperties().Select(f => f.Name).ToList();

        var request = context.HttpContext.Request;
        request.Body.Position = 0;

        using (var reader = new StreamReader(request.Body))
        {
            //get request body content
            var bodyString = reader.ReadToEnd();                

            //transfer content to json
            JObject json = JObject.Parse(bodyString);

            //if json contains fields that do not exist in Model, add model error                
            foreach (JProperty property in json.Children())
            {
                if (!listOfFieldNames.Contains(property.Name))
                {
                    context.ModelState.AddModelError("Filed", "Field does not exist");                      
                }
            }
        }
        base.OnActionExecuting(context);
    }
}

2.对您的操作使用过滤器:

[HttpPost]
[CompareFieldsActionFilter]
public async  Task<ActionResult<Person>> Post([FromBody] PersonDto personDto)
{
   if (ModelState.IsValid)
    {
       // do things
    }
  // do things
}

推荐阅读