Aspwebapi判断请求参数是否为空简易方法ModelValidation判断请...

Aspwebapi判断请求参数是否为空简易⽅法ModelValidation判断请。
。。
通常情况下,对于那些经常为别⼈提供数据接⼝的开发⼈员来说,对于调⽤⽅传递过来的参数都会有验证处理。例如:
if (string.IsNullOrEmpty(entity.Name))
{
//当姓名为空时,.........
}
if (entity.Age<0 || entity.Age>100)
{
简易过滤器
//当年龄⼩于0或⼤于100时,有的⼈可能超过⼀百岁,我希望我的有⽣之年Age>100,emm,.........
}
if (string.IsNullOrEmpty(entity.PhoneNum))
{
//当电话号码为空时,.........
}
if (!string.IsNullOrEmpty(entity.PhoneNum))
{
Regex regex = new Regex("^1[34578]\\d{9}$");
var result=regex.IsMatch(entity.PhoneNum);
if (!result)
{
//当电话号码格式不合法时,.........
}
}
//以下还有50个字段需要验证,是不是有种绝望的感觉,有⽊有?有⽊有?有⼈可能会跟调⽤者说,某个字段必须怎么怎么样,有些⼈就喜欢故意传错,故意刁钻,到头来,最苦逼的还是写接⼝的⼈。有时候⼀个系统有⼗⼏⼆个接⼝,光验证的代码就⼀⼤堆,真的有时候不想写,都说程序猿是最聪明的⼀批⼈,⾃然有好的解决⽅法。
C# webapi 有⼀种叫模型验证的东西,在java⾥⾯,应该有⼀种注解的东西可以处理。
在ASP.NET Web API中,你可以使⽤命名空间的注解属性来设置模型属性的验证规则。考虑以下模型:
public class Personnel
{
[Required(ErrorMessage = "Name参数不能为空")]//Required 验证这个参数不能为空 ErrorMessage:为空时⾃定义错误信息
public string Name { get; set; }
[Range(1,100, ErrorMessage="Age参数只能是⼤于1,⼩于100")]//Range 验证值只能在某些范围内,只适⽤于Int类型的字段
public int Age { get; set; }
[Required(ErrorMessage = "电话号不能为空")]
[RegularExpression("^[1]+[3,4,5,7,8]+\\d{9}", ErrorMessage = "PhoneNum不合法的电话号码格式")]//RegularExpression ⽤正则验证字段的合法性,多⽤于⾝份证、电话号码、邮箱、等等...
public string PhoneNum { get; set; }
}
这样的话就可以节省⼤量冗余代码,那么,接下来如何去处理呢?
在接⼝请求之前,我们可以对客户端传过来的数据进⾏模型验证处理,对于webapi⽐较熟悉的⼈应该知道过滤器,不知道的可以看我前⾯的⽂章,如何使⽤webapi三⼤过滤器,过滤器是基于AOP,⾯向切⾯的编程思想。
在这⾥我们⽤的ActionFilterAttribute过滤器,只要继承这个接⼝并且实现其中的OnActionExecuting⽅法就⾏。具体实现如下:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
namespace Huajie.Application.Web.Controllers.Apis
{
public class ModeActionFilter: ActionFilterAttribute
{
///<summary>
///接⼝请求前验证数据
///</summary>
///<param name="actionContext">上下⽂</param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
// Return the validation errors in the response body.
// 在响应体中返回验证错误信息
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
actionContext.Response =actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new
{
code= HttpStatusCode.BadRequest,//返回客户端的状态码
success = false,
error = errors//显⽰验证错误的信息
});
}
}
}
}
在WebApiConfig.cs⾥⾯注册⼀下这个过滤器
config.Filters.Add(new ModeActionFilter());
请求⽅法⽰例:
[Route("test")]
[HttpPost]
public string Test([FromBody] Personnel entity )
{
return"成功!";
}
⾃定义返回(返回请求成功HttpStatusCode.OK 并且有多个错误取第⼀个即可)actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new ResultStr()
{
content = null,
isSuccess = false,
message = actionContext.ModelState.FirstOrDefault().Value.Errors.FirstOrDefault().ErrorMessage
});

本文发布于:2024-09-22 03:55:49,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/3/351137.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:验证   模型   参数   返回   属性   过滤器   字段
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议