webapi 传入参数校验

2021/12/19 6:21:52

本文主要是介绍webapi 传入参数校验,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 /// <summary>
    /// 传入参数校验过滤器
    /// </summary>
    public class ValidateReqModelFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }
  [ValidateReqModelFilter]
    public class TestController : ControllerEduBase
    {
            /// <summary>
            /// 测试
            /// </summary>
            [HttpPost]
            [Route("api/Test/saveSchool")]
            public JsonResult<ResponseMessage> Test(ReqTest req){
          var result = new object();
          return Json(result);
            }
    }    
public class ReqSaveSchool
    {
        /// <summary>
        /// token
        /// </summary>
        [Required(AllowEmptyStrings = false, ErrorMessage = "Token is validate")]
        public string Token { get; set; }

        /// <summary>
        /// id
        /// </summary>
        [RegularExpression(@"^[0-9]\d*$",ErrorMessage = "Id is validate")]
        public int Id { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        [Required]
        [StringLength(50,ErrorMessage = "Name is exceeding the length limit")]
        public string Name { get; set; }
    }

测试结果:如果输入参数校验失败,不会进入controller,直接返回错误信息。

 

转载于:https://www.cnblogs.com/teng-0802/p/11593105.html

----------------------------------------------------------------------新的

Asp.net webapi 判断请求参数是否为空简易方法 Model Validation 判断请求参数是否为空

 

通常情况下,对于那些经常为别人提供数据接口的开发人员来说,对于调用方传递过来的参数都会有验证处理。例如:

复制代码
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中,你可以使用System.ComponentModel.DataAnnotations命名空间的注解属性来设置模型属性的验证规则。考虑以下模型:

复制代码
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
                });
复制代码

 

 

 

 

 

 

 

 



这篇关于webapi 传入参数校验的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程