惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
S
Securelist
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Schneier on Security
Schneier on Security
P
Proofpoint News Feed
Latest news
Latest news
C
CXSECURITY Database RSS Feed - CXSecurity.com
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
美团技术团队
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
AWS News Blog
AWS News Blog
V2EX - 技术
V2EX - 技术
云风的 BLOG
云风的 BLOG
博客园 - 聂微东
腾讯CDC
月光博客
月光博客
G
Google Developers Blog
F
Fortinet All Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
Hacker News - Newest:
Hacker News - Newest: "LLM"
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
Apple Machine Learning Research
Apple Machine Learning Research
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
WordPress大学
WordPress大学
Spread Privacy
Spread Privacy
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Threatpost
N
News and Events Feed by Topic
Y
Y Combinator Blog
J
Java Code Geeks
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Project Zero
Project Zero
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
C
CERT Recently Published Vulnerability Notes
小众软件
小众软件
有赞技术团队
有赞技术团队
罗磊的独立博客
Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Proofpoint News Feed

博客园 - Frank.Cui

Scriban语言手册中文版 开源文件服务器file-service介绍 记一次redis病毒分析笔记 推荐一个比FiddlerCore好用的HTTP(S)代理服务器 适用于 Windows 10 的触摸板手势 vi命令示例大全 Linux系统中的常用命令 解决Protobuf生成的C#代码命名不规范问题 使用Markdown写作 DapperPoco -- 基于Dapper的、轻量级的、高性能的、简单的、灵活的ORM框架 使用StyleCop.Analyzers进行代码审查 推荐一款好用的WSL终端模拟器 使用ssh公钥密钥自动登陆linux服务器 Fiddler插件开发 - 实现网站离线浏览功能 自动化CodeReview - ASP.NET Core依赖注入 10个有关RESTful API良好设计的最佳实践 ASP.NET Core 获取控制器上的自定义属性 [转] Autofac创建实例的方法总结 PetaPoco - 轻量级高性能的ORM框架(支持.NET Core)
自动化CodeReview - ASP.NET Core请求参数验证
Frank.Cui · 2017-02-14 · via 博客园 - Frank.Cui

自动化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

使用ValidateModel需要保证:

1. 项目中有统一的返回格式;例如:JSON或XML

2. 所有接口有统一的公共字段;例如:

{
     "errCode": 0, //0成功,其它值失败
     "errMsg": "失败时的错误消息",
     "data": {
         //成功时的返回数据
         …
     }
 }

其实对于优秀的项目架构设计,以上2点都不是问题,只有“统一”才可以更好的抽象化代码,封装通用框架。

写到这里其实还不完美,如果Login上的[ValidateModel]忘加了呢?

编译也能通过,测试时还不容易发现。但这实实在在是个BUG,没有校验参数合法性啊。

自动化CodeReview之AutoReview

  我始终坚信再牛掰的程序员也有疏忽的时候,有时写着写着就忘加了。

能不能在忘加的时候提醒一下呢?答案是:可以的。

本系列的第1篇我写了关于【ASP.NET Core依赖注入】的自动化CodeReview,在写参数验证自动化CodeView时我发现自动化CodeView其实有很多可写的。

为了将零散的代码整理到一起,也为了以后可以持续维护下去,我重开了一个项目,项目名暂定AutoReview,PS:大家如果有更好的名字欢迎赐教

项目代码我放到了github上,地址为:https://github.com/md-frank/AutoReview

先来看下它的用法:

先在Startup.ConfigureServices方法最后加入如下代码:

public void ConfigureServices(IServiceCollection services)
{
    //注册服务代码放到此处

    //此段放在最后
    if (_env.IsDevelopment())
    {
        services.AddAutoReview(
            new DependencyInjectionAssert(),
            new ValidateModelAssert()
            {
                ValidateModelAttributeType = typeof(ValidateModelAttribute)
            }
        );
    }             
}

AddAutoReview方法接受一个IAssert数组,表示要使用的断言,目前支持2个断言DependencyInjectionAssert、ValidateModelAssert

然后在在Startup.Configure方法中加入如下代码:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    //使用AutoReview,代码位置任意
    if (_env.IsDevelopment())
        app.UseAutoReview();
}

至此如果任意断言验证失败,UseAutoReview方法都会抛出异常,并提示问题代码的具体位置,终止项目运行。

现在你就可以在开发过程中发现BUG了,解决问题后重新运行即可。