Automated CodeReview and codereview

Source: Internet
Author: User

Automated CodeReview and codereview

Automated CodeReview series Directories

 

Parameter verification implementation

During server development, you often need to verify the validity of the parameters passed in by the client. The following methods are usually used in ASP. NET Core:

Public class LoginModel {[Required (ErrorMessage = "Account cannot be blank")] public string Account {get; set;} [StringLength (12, MinimumLength = 6, errorMessage = "the Password length should be between 6-12 characters")] public string Password {get; set ;}}
Public IActionResult Login (LoginModel model) {if (ModelState. isValid) {// parameter verification passed, processing login logic} else {// parameter verification failed, returns the first error var firstErrorMsg = ModelState. getFirstErrorMessage (); return Content (firstErrorMsg );}}

Although the parameter can be verified by such writing, it is still necessary to write another if... else.... Can it be simplified to verification with only one line of code?

The answer is yes. First, let's look at the simplified usage:

[ValidateModel] public IActionResult Login (LoginModel model) {// This field indicates that the parameter has been verified}

The above code will return if the Account is null:

{"ErrCode": 3, "errMsg": "The account cannot be blank "}

The difference is that a [ValidateModel] is added to the Action, and the parameter validation logic is processed in ValidateModelAttribute. This is the usage of the Action filter in MVC. I will not expand the parameter length limit, directly run the Code:

Namespace Mondol. WPDental. web. filters {// <summary> // make sure that the Model of the current Action is verified. Otherwise, the error response result is returned. // </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

 

To use ValidateModel, you must ensure that:

1. The project has a unified return format; for example, JSON or XML

2. All interfaces have uniform public fields. For example:

{"ErrCode": 0, // 0 successful, other values failed "errMsg": "error message upon failure", "data": {// returned data upon success... }}

In fact, the above two points are not a problem for excellent project architecture design. Only "Uniform" can better abstract code and encapsulate general frameworks.

 

Writing it here is not perfect. What if the [ValidateModel] On Login is missing?

Compilation can also pass, and it is not easy to find during testing. However, this is actually a BUG and does not verify the validity of the parameter.

 

Automatic CodeReview AutoReview

I always believe that even the cool programmers are negligent, sometimes they forget to write.

Can you remind me when you forget to add it? The answer is: yes.

 

I wrote automation CodeReview about [ASP. NET Core dependency injection] In the 1st articles of this series. When I wrote parameter verification automation CodeView, I found that automation CodeView actually has a lot to write.

In order to organize the scattered Code together and maintain it continuously, I re-opened a project named AutoReview. PS: If you have a better name, please kindly advise me.

Project code I put on github at: https://github.com/md-frank/AutoReview

 

Let's take a look at its usage:

Add the following code at the end of the Startup. ConfigureServices method:

Public void ConfigureServices (IServiceCollection services) {// register the service code here // put this segment at the end if (_ env. isDevelopment () {services. addAutoReview (new DependencyInjectionAssert (), new ValidateModelAssert () {ValidateModelAttributeType = typeof (ValidateModelAttribute )});}}

The AddAutoReview method accepts an IAssert array, indicating the assertions to be used. Currently, two assertions DependencyInjectionAssert and ValidateModelAssert are supported.

 

Then add the following code to the Startup. Configure method:

Public void Configure (IApplicationBuilder app, ILoggerFactory loggerFactory) {// use AutoReview. if (_ env. IsDevelopment () app. UseAutoReview ();}

 

If any assertion fails to be verified, the UseAutoReview method throws an exception and prompts the specific location of the problem code to terminate the project.

Now you can find a BUG during the development process. After solving the problem, run it again.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.