标签:http postman 业务 自动 over href value 必须 action
原文:.Net Core Web Api使用模型验证验证参数合法性
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吗?这时候模型验证就发挥作用啦。
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且会根据定义的提示去提示前端参数哪里不合法。但是很多小伙伴的返回值都是通用的,怎么把这些提示放到自己的通用返回值里面呢?
public class ResponseDto {/// <summary> /// 详细错误信息 /// </summary> public string message { get; set; } /// <summary> /// 具体业务参数 /// </summary> public object data { get; set; } }
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) { resul127.0.0.1ssage += error.ErrorMessage + ","; result.data = "{}"; } } resul127.0.0.1ssage = resul127.0.0.1ssage.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来判断模型验证是否通过。
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 = "" } }); }); }
模型验证通过
.Net Core Web Api使用模型验证验证参数合法性
标签:http postman 业务 自动 over href value 必须 action
原文地址:https://www.cnblogs.com/lonelyxmas/p/12031139.html