. Net advanced, teaches you how to build an enterprise model data interception layer, dynamic control field verification,. net Field

Source: Internet
Author: User

. Net advanced, teaches you how to build an enterprise model data interception layer, dynamic control field verification,. net Field

Now you have a web project with MVC Architecture, and you need to complete a registration function.

The front-end transmits three values to your Controller: account, password, and email.

Now you need to judge in the Controller that the account name, password, and email address cannot be blank, and the name and password cannot exceed 16 characters.

The above figure is just an ideal small example. In actual development, it is possible that more than a dozen fields may be uploaded at a time.

In actual development, we usually replace these three parameters with an object class for reusability.

As shown in the following figure.

Note: This step has a knowledge point called model verification. If you are not familiar with it, you can use Baidu. MVC will automatically deserialize the parameters to the corresponding entity class through certain rules, however, because my example uses the webapi mode and the writing method is slightly different, you must add a [FromBody] before the parameter to automatically deserialize it.

As to why automatic deserialization is specific, this article is not the topic I want to talk about, so if you are interested in it, you can use Baidu: ModelBinder under MVC.

Interception layer decoupling

Now, I think this method of writing entity class verification to the controller is not very good. If there are many business rules, the verification code will be very huge, if the entire project adopts this verification mode, it seems a bit bloated in the maintenance phase after my day. The entity class relies on the Controller Method for verification, I have to find this entity class first, and then think carefully about which methods use this entity class, what verification judgments have been made, and then maintain it.

So can I remove the entity class verification step in the Controller method, not write it into the Controller method, write it in another place, and manage it in a unified manner, implements entity class verification and separates the method business logic in the controller.

This kind of behavior operation is a bit like httpModule, and the idea is that the design pattern is called to reduce coupling.

How can this problem be solved?

We can directly add verification in the Entity class,

As shown above, the [Required], [StringLength], and [RegularExpression] are called verification features. They are encapsulated by the. net Framework and will verify the fields of the Annotation Feature.

[Required] the input is limited. [Required (ErrorMessage = "Enter the user name")]

[StringLength] specifies the length. [StringLength (10, ErrorMessage = "length cannot exceed 10 characters")]

[Range] limits the value Range. [Range (0,120, ErrorMessage = "age Range between 0 and 120")]

[RegularExpression] specifies that the regular expression must be satisfied. [RegularExpression (@ "^ \ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w +) * $ ", ErrorMessage =" enter Email format ")]

[Compare] limits the fields to be equal to, [Compare ("pwd", ErrorMessage = "two passwords must be consistent")] // The field value of this feature annotation must be equal to the pwd Field Value

. Net also encapsulates a few, the five are the most used (of course, you can also customize this verification feature, please Baidu: mvc ValidationAttribute for in-depth understanding ).

How can I determine the feature after I mark it?

Let's take a look at the writing method in the Controller method:

Use ModelState. IsValid to determine the verification result. If all the marked features on the object class meet the conditions, the value is true; otherwise, the value is false.

Therefore, because this model authentication is a global model, you should register it at the interception layer separately.

This Code indicates that the name of the method is determined every time before the Controller method is entered. If any of the three methods include Insert, check, and update, all requests are intercepted and verified (the model verification result is determined). If the value is false, a 400 status code is returned to the client.

Then register: (the registration is just an example, because I am a webapi and only intercept http)

 

The model is responsible for entering rules, and the verification is done by a dedicated validators. The logic is written by a dedicated logic engineer, so that they can perform their respective duties.

However, this is only the first step!

(With your daily development, you will certainly encounter this situation)

The user entity class focuses on the registration method. To put it bluntly, it is written for the registration method,

Now I want to write a logon method.

However, when logging on, I do not need to fill in an email, but only need to fill in the account and password to verify these two fields.

However, the [Required] and [RegularExpression] verification is performed on the email in my entity class, which leads to an error if the logon method continues to use this user entity class, the system returns a 400 verification code.

How can I solve this problem? Do you need to re-create a model? Again? There are only three fields. What should I do if there are more than a dozen fields, more than 20 fields in some tables?

Re-building a model is definitely not feasible, so it has lost the original intention of reusing and performing their respective duties.

Find a solution! Online, etc!

...

Advanced model verification: free control of fields to be verified

Baidu once, there were no tutorials on the internet, no results were found in the blog Park, and no results were delivered in the group, but this situation was often encountered!

There are several ideas. The first is to control these verification features in the class by some means, or to control attribute fields in the class, such as enabling or disabling, however, c # cannot disable attribute fields, and these verification features in the control class are a bit confusing. Microsoft encapsulates them. You have to decompile the source code and then refactor them? Or do you need to use custom verification features without the verification features encapsulated by these frameworks, and then write the control methods in them? This is too troublesome and contrary to the original intention. Custom ModelBinder? More nonsense.

If nothing happens, you cannot find a breakthrough from the feature itself. At this time, I will move the goal to ModelState. IsValid to implement it in another way.

We found that the GetEnumerator method is implemented, so we can traverse it and get the name and status of the field property bound to the feature.

To implement free control of fields that need to be verified, you can only use custom feature annotation in the method header for implementation.

The ideal final presentation effect should be as follows:

Chart:

 

Or

 

 

Usage:

If the KeepZ feature exists on the method header, it enters the free control verification field status.

 

[KeepZ ("Field 1", "Field 2")] indicates that only field 1 and Field 2 are verified.

[KeepZ (false, "Field 3")]: all fields except Field 3 are verified.

 

 

Let's put down the specific implementation code:

 

 public override void OnActionExecuting(HttpActionContext actionContext)        {            if ((actionContext.ActionDescriptor.ActionName.ToUpper().Contains("INSERT") || actionContext.ActionDescriptor.ActionName.ToUpper().Contains("CHECK") ||                 actionContext.ActionDescriptor.ActionName.ToUpper().Contains("UPDATE")))            {                var ia = actionContext.ActionDescriptor.GetCustomAttributes<KeepZ>();                if (ia.Count != 1)                {                    goto result;                }                foreach (KeyValuePair<string, ModelState> item in actionContext.ModelState.ToArray())                {                    if (ia[0].Modes == false)                    {                        foreach (string PropertysValue in ia[0].Propertys)                        {                            if (item.Key.Contains(PropertysValue))                            {                                actionContext.ModelState.Remove(item.Key);                            }                        }                    }                    else                    {                        bool re = false;                        foreach (string PropertysValue in ia[0].Propertys)                        {                            if (item.Key.Contains(PropertysValue))                            {                                re = true;                            }                        }                        if (re == false)                        {                            actionContext.ModelState.Remove(item.Key);                        }                    }                }                result: if (!actionContext.ModelState.IsValid)                {                                      actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);                                                         }            }        }
/// <Summary> /// // </summary> public class KeepZ: Attribute {public string [] Propertys = null; public bool Modes = true; public KeepZ (params string [] Property) {Propertys = Property;} public KeepZ (bool Mode, params string [] Property) {Propertys = Property; Modes = Mode ;}}

In this way, we need to re-build the low-end method such as Model. Currently, most MVC architectures use this verification mode, but there is no free solution to select verification fields, we can only build a new entity class. In contrast, we don't have to learn the essence of this interception layer model verification. Instead, we can learn only a model. Instead, we cannot help ourselves, so I wrote this article and shared it with you. I added KeepZ to control the fields to be verified. It is actually reusable, and the logic and interception layers are implemented.

The Demo is small, but in this case the solution is not found in the blog garden. It should be the first article in the garden.

 

Author: xiaozeng
Source: http://www.cnblogs.com/1996V/p/7423834.html welcome to reprint, but any reprint must retain the complete article, in the display of the title and the original link. If you have any questions or authorization negotiation, please leave a message for me
. Net Communication Group, QQ group: 166843154 desire and struggle

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.