.Net Core 使用模型验证

  • 再开发过程中免不了要去验证参数的合法性,模型验证就是帮助我们去验证参数的合法性,我们可以在需要验证的model属性上加上Data Annotations特性后就会自动帮我们在action前去验证输入数据的合法性。
  1. 定义一个Person类
    public class PersonDto
    {
    public string Name { get; set; } public string Phone { get; set; } public int Age { get; set; } }

    Person类有三个属性,姓名,电话,年纪。

  2. 创建一个接口并以Person作为input参数并且返回input对象
    public PersonDto Demo(PersonDto input)
    {
        var str = string.Empty;
        PersonDto dto = new PersonDto
        {
          Name = input.Name,
          Age=input.Age,
          Phone=input.Phone,
         };
       return dto;
     }

  3.用postman来调用这个接口  

    

很明显我传入的参数是不合法的,但是接口依旧执行了。 那怎么去验证参数的合法性呢?在接口里面写if吗?这时候模型验证就发挥作用啦。 

  1. 修改之前的Person类,引入using System.ComponentModel.DataAnnotations;

    public class PersonDto
        {
            [Required(ErrorMessage = "姓名不能为空"), MaxLength(10, ErrorMessage = "名字太长啦"), MinLength(0, ErrorMessage = "名字太短")]
           [ RegularExpression(@"^[\u4e00-\u9fa5]+$", ErrorMessage = "姓名必须是中文")]
            public string Name { get; set; }
    
            [Required(ErrorMessage = "手机号码不能为空"), RegularExpression(@"^\+?\d{0,4}?[1][3-8]\d{9}$", ErrorMessage = "手机号码格式错误")]
            public string Phone { get; set; }
    
            [Range(1, 1000, ErrorMessage = "年纪必须在0-99之间")]
            public int Age { get; set; }
        }

    在次调用这个接口 

    

   如果参数参数的不合法会直接400且会根据定义的提示去提示前端参数哪里不合法。但是很多小伙伴的返回值都是通用的,怎么把这些提示放到自己的通用返回值里面呢?

  1. 定义一个通用的返回值

        public class ResponseDto
        {/// <summary>
            /// 详细错误信息
            /// </summary>
            public string message { get; set; }
    
            /// <summary>
            /// 具体业务参数
            /// </summary>
            public object data { get; set; }
        }
  2. 定义一个CustomResultFilter

        public class CustomResultFilter : ActionFilterAttribute
        {
            public override void OnResultExecuting(ResultExecutingContext context)
            {
    
                if (!context.ModelState.IsValid)
                {
                    ResponseDto result = new ResponseDto();
    
                    foreach (var item in context.ModelState.Values)
                    {
                        foreach (var error in item.Errors)
                        {
                            result.message += error.ErrorMessage + ",";
                            result.data = "{}";
                        }
                    }
                    result.message = result.message.TrimEnd(',');
                    context.Result = new JsonResult(result);
                }
                else
                {
                    var result = context.Result as ObjectResult ?? null;
                    context.Result = new OkObjectResult(new ResponseDto
                    {
                        message = "成功",
                        data = result == null ? "{}" : result.Value
                    });
                    base.OnResultExecuting(context);
    
                }
            }
    
            public override void OnActionExecuting(ActionExecutingContext context)
            {
            }

    使用ModelState.IsValid来判断模型验证是否通过。

  3. 配置过滤器

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc(options =>
                {
                    options.Filters.Add(typeof(CustomResultFilter));
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Info
                    {
                        Title = " API",
                        Version = "v1",
                        Description = "RESTful API",
                        TermsOfService = " Service",
                        Contact = new Contact { Name = "", Email = "", Url = "" }
                    });
                });
            }
  4. 测试

  

   模型验证通过

  

猜你喜欢

转载自www.cnblogs.com/stutlh/p/11934326.html