自动化CodeReview系列目录

  1. 自动化CodeReview - ASP.NET Core依赖注入
  2. 自动化CodeReview - ASP.NET Core请求参数验证

 

参数验证实现

在做服务端开发时经常需要对客户端传入的参数进行合法性验证,在ASP.NET Core中通常会使用如下方式:

public class LoginModel
{
    [Required(ErrorMessage = "账号不能为空")]
    public string Account { get; set; }
    [StringLength(12, MinimumLength = 6, ErrorMessage = "密码长度应介于6-12个字符之间")]
    public string Password { get; set; }
}
public IActionResult Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        //参数校验通过,处理登陆逻辑
    }
    else
    {
        //参数校验失败,返回第一个错误
        var firstErrorMsg = ModelState.GetFirstErrorMessage();
        return Content(firstErrorMsg);
    }
}

这么写虽然可以验证参数了,但还是要多写一个if...else...,能不能简化成只用一行代码就实现验证呢?

答案是:可以的,先看简化后的用法:

[ValidateModel]
public IActionResult Login(LoginModel model)
{
    //能执行到此处表示参数已验证通过
}

以上代码如果Account传空会返回:

{
     "errCode": 3,
     "errMsg": "账号不能为空"
}

与之前的区别是在Action上加了一个[ValidateModel],参数校验逻辑在ValidateModelAttribute里处理,这是MVC里Action过滤器的用法,篇幅限制我就不展开了,直接上代码:

namespace Mondol.WPDental.Web.Filters
{
    /// <summary>
    /// 确保当前Action的Model是已验证的,否则返回错误响应结果
    /// </summary>
    public class ValidateModelAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var result = new Result(ResultErrorCodes.ArgumentBad, context.ModelState.GetFirstErrorMessage());
                context.Result = new JsonResult(result);
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}
View Code

相关文章:

  • 2018-03-29
  • 2021-10-28
  • 2021-06-08
  • 2021-07-26
  • 2020-06-12
  • 2020-05-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
  • 2022-12-23
相关资源
相似解决方案