NETCORE - ValidationAttribute 属性验证

NETCORE - ValidationAttribute 属性验证

 创建 .net6 web api 项目:NETCORE.TAttribute.Valide

创建 model 类

using System.ComponentModel.DataAnnotations;

namespace NETCORE.TAttribute.Valide
{
    public class PersonalRequest
    {
        public int Id { get; set; }

        [Required]
        [MinLength(2), MaxLength(20)]
        public string Name { get; set; }

        public string Sex { get; set; }

        [Required]
        [MinLength(2), MaxLength(20)]
        public string Address { get; set; }

    }
}

 

 

创建 web api 控制器

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace NETCORE.TAttribute.Valide.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpPost]
        [Route("WebAPIApply")]
        public IActionResult WebAPIApply(PersonalRequest request)
        {
            return Ok();
        }
    }
}

 

 

验证方式1:

创建过滤器类: ModelValidateFilter.cs

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace NETCORE.TAttribute.Valide
{
    public class ModelValidateFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                var allErrors = context.ModelState.Values.SelectMany(v => v.Errors);
                var message = string.Join(" | ", allErrors.Select(e => e.ErrorMessage));
                context.Result = new JsonResult(new { results = allErrors });
            }
            await next();
        }
    }
}

 

 

 注册:Filter 创建完成后,需要注册一下,这里我们使用全局模式。如下

 在 Program.cs 中

builder.Services.AddMvc(opt =>
{
    opt.Filters.Add(new ModelValidateFilter());
});

 

 

测试:在 swagger 中测试 

传参:

{
  "id": 0,
  "name": "c",
  "sex": "lieicm",
  "address": "a"
}

 

 

 

  

 

 

 

 

 

在代码中手动验证:

验证方式2:

Personal personal = new Personal();
// personal.Name = "D";
ValidationContext validationContext = new ValidationContext(personal);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(personal, validationContext, results, true); 

 

 

 控制器中测试CanToIntAttribute

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace NETCORE.TAttribute.Valide.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpPost]
        [Route("WebAPIApply")]
        public IActionResult WebAPIApply(PersonalRequest request)
        {
            PersonalRequest model = new PersonalRequest()
            {
                Id = 1,
                Name = "a",
                Sex = "leixm",
                Address = "c"
            };

            ValidationContext validationContext = new ValidationContext(model);
            List<ValidationResult> results = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(model, validationContext, results, true);

            return Ok();
        }
    }
}

 

 

自定义 ValidationAttribute 

创建验证类 CanToIntAttribute.js 

using System.ComponentModel.DataAnnotations;

namespace NETCORE.TAttribute.Valide
{
    public class CanToIntAttribute : ValidationAttribute
    {
        /// <summary>
        /// IsValid 为 false 时,提示得 error 信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            return $"{name} need to int";
        }

        /// <summary>
        /// 验证当前字段得结果
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            int num = 0;
            return int.TryParse(Convert.ToString(value), out num);
        }
    }
}

 

 

[CanToInt]
 public string Sex { get; set; }

 

调用上面的验证方式即可。

 

 

 

 

 

 

 

 

 

 

 

 

引用:https://blog.csdn.net/weixin_46785144/article/details/124178106

 

posted @ 2022-11-03 15:22  无心々菜  阅读(241)  评论(0编辑  收藏  举报