Asp. NET all-stack development using server-side validation in MVC (ii)

Source: Internet
Author: User
Tags reflection static class
First of all, this blog post is perfect. Asp. NET full stack development in the MVC using the server authentication, so repeat the content, I do not too much elaboration, a lot of problems are in practice to find, and then to improve, this blog is the same, established in the read. Asp. NET All-stack development is based on the use of server-side validation in MVC.

In the previous article, although we completed the service-side validation, we still need to invoke the validator in action to verify it, like this.

   [HttpPost]               Public ActionResult validatortest (person model)        {var result = this. ValidatorHub.PersonValidator.Validate (model);                        if (result. IsValid)            {                 return Redirect ("https://www.baidu.com");            } Else            {this                 . Validatorerrorhandler (result);            }                        return View ();        }

Very hateful, if I need to verify, I need to write in every action like this, an experiment is just, if you really want to do in each action like this, I think you will be very annoying the code. At least I think so. So I hate the writing I've been writing.

Now what do I want to do? We know that MVC has a built-in data check. It's not too much to introduce here, (there are a number of advantages to the occasional proper shining wheel). Here is a brief description of its usage.

  [HttpPost]          Public ActionResult validatortest (person model)        {            if (modelstate.isvalid)            {//OK}                        return View ();        

It's a lot easier to write than we did before, but I still think he's going to call modelstate.isvalid in every action, though there's only one if, but that's not what I want, and I want it to be like this.

  [HttpPost]              Public ActionResult validatortest (person model)        {////  A lot of code                        //                            return Redirect (" Https://www.baidu.com ");        }

Don't interfere with my normal programming, and I don't do anything repetitive.

In other words, the data is actually verified before executing my action.

So we think of the filter,onactionexecuting that MVC gives us, open our Controllerex, rewrite onactionexecuting inside, he has a parameter actionexecutingcontext , by name we understand roughly that this parameter is an action-related context, and he must have loaded the action-related data

I will not ink, first directly on the code, in fact, these code is just I just wrote out, I am not very understanding of this parameter, through a one to try, slowly have to try out.

 protected override void OnActionExecuting (ActionExecutingContext filtercontext) {var exist                        Error = false; foreach (var value in filterContext.ActionParameters.Values) {var modelvalidato Rpropertyinfo = this. Validatorhub.gettype (). GetProperty (value. GetType ().                Name + "Validator"); if (modelvalidatorpropertyinfo! = null) {var modelvalidator = model Validatorpropertyinfo.getvalue (this.                    Validatorhub) as IValidator;                    var Validateresult = modelvalidator.validate (value); if (!validateresult.isvalid) {this.                        Validatorerrorhandler (Validateresult);                    Existerror = true; }}} if (Existerror) {viewdata["Error"] = Dic Error;                Filtercontext.result = View (); } base.        OnActionExecuting (Filtercontext); }

In onactionexecuting, we first defined a existerror to determine if the validation failed, and then we traversed the filterContext.ActionParameters.Values

In Filtercontext, we see that actionparameters is about the action parameter, and by debugging I find that he is a collection whose key is the parameter name, for example, to take our person.

[HttpPost]             Public ActionResult validatortest (person model)        {////  A lot of code                        //                            return Redirect ("https:// Www.baidu.com ");        }

There is a data in the Filtercontext.actionparameters collection whose key is the "model" value. Model

So we can take all the parameters of each action by traversing FilterContext.ActionParameters.Value, and each parameter passes. GetType (). Name can take out his type name, such as the model type is person so filtercontext.actionparameters["model". GetType (). Name is "person".

Know what the entity is, how to get a specific validator? Think of our authenticator config person = Personvalidator That's too easy, it's not a one-to-two relationship, but it's not always possible to go back to the factory via a switch, which also requires a factory approach. Of course not, it will use the powerful reflection technology provided by our. NET

Sometimes we have an anonymous object, it is an object, and do not know what the type is, how to take its properties?

I have a method here that he can solve the problem.

public static class Reflecthelper    {public                static object Getpropertybyanonymousobject (String propertyname, Object obj)        {                        var property = obj. GetType (). GetProperties (). Where (p = = P.name = = propertyname). FirstOrDefault ();            if (property = = null)            {                                throw new Exception (string. Format ("{0} object not defined {1} attribute", nameof (obj), nameof (PropertyName)));            }                        Return property. GetValue (obj);        }    }

From the use, pass a property name and object in and return the property of an object.

Let's see what's been done inside.

First get the type, and then get the execution of the property, eh, this property is not a real property oh, this is the PropertyInfo type, is the reflection of the data type, it is not a real property value, but if we want to get the real property value what to do? In fact, just call his getvalue, he has a parameter, this parameter refers to get the property on that object, so the object is passed in.

With this foundation, we understand the purpose of the person, there is an object called Validatothub inside there is a property personvalidator, So we just need to get a Personvalidator property called Validatorhub object on the line. (The person is replaceable, based on the type of the parameter, as explained above, here with person example)

Now there is a problem, we take the Personvalidator is an object type, object Type I can not use Ah, we can not display the conversion to a specific type, because who knows what the specific type is. If the writing is dead, it will be cold. That certainly can not use a switch to maintain AH, that does not increase the workload.

We slowly found that personvalidator inherited from abstractvalidator<person> it is clear that its base class also needs a specific type, no, continue to go up, eh, found the abstractvalidator<t > Inherits from IValidator, and IValidator defines the Validate method. This is not good, I as for the IValidator type, it can be used. Here is used (the Richter conversion principle). I try to write it easy to understand, but also to mention a lot of basic things, but not to be exhaustive, so it is built on a part of the foundation. (Of course, the more important thing is that through the problems I have encountered later in the design of the generic class structure, I have to inherit a non-generic interface, if Fluentvalidator does not inherit from IValidator but only inherits from Ivalidator<t> In fact, from the simple use of speaking, and there is no impact ah, but to the we just here, the problem is out, so this is to give us a lesson on the ground!

Now I can verify it here, and we know that value is the model, so just validate it and verify that it returns a Validationresult type. I will not explain the next thing, I believe the last chapter is very clear. Finally, based on whether there is an error in advance processing, if there is an error, the direct return to the view rendering error, even our action is not executed. Well, here we speak yesterday onactionexecuted can be directly delete pull.

We will now test the validation code in the Validatortest.

        [HttpPost]                Public ActionResult validatortest (person model)        {////  A lot of code                            //                            return Redirect ("https:// Www.baidu.com ");        }

Put a breakpoint in the validatortest, and then fill it out, and submit it directly.

The breakpoint is not triggered, but the error message is rendered. Try a few more times ~.

Also not triggered.

Well, let's do a proper verification.

The breakpoint is triggered. And the value has passed the checksum

F5 release, finally our page jumps to the www.baidu.com.

Well, the little friends are not going to change the code to make a happy life.

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.