如何验证模型验证中的非法字段 [英] How to validate for illegal fields in Model Validation

查看:21
本文介绍了如何验证模型验证中的非法字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受PersonDto的.NET Core2.2Web-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"
}

我预计模型验证会抱怨"Name"字段不存在。

如何检查非法字段?

推荐答案

您可以使用ActionFilterReflection将请求正文内容与模型字段进行比较。如果存在意外字段,请手动添加模型错误,ModelState.IsValid将为False。

1.创建ActionFilter

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
}

这篇关于如何验证模型验证中的非法字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆