<<ABP framework >> Validating data transfer objects

Source: Internet
Author: User
Tags app service

Document Directory

The content of this section:

    • Brief introduction
    • Using data annotations
    • Custom validation
    • disabling validation
    • Normalization

Brief introduction

An application's input should be validated first, this input may come from the user or another application, in a Web application, the validation is usually implemented two times: on the client and on the server side, the client authentication is for the user experience, it is best to first check a form and show the user invalid input, But the validation of the service side is more decisive and necessary.

Server-side validation is typically implemented in an application service or controller (typically, all services get data from the presentation layer). An app service should check (validate) the input before using it. The ABP provides a basic construct that automatically validates all of the following three entries for an application:

    • All application service methods.
    • Action for all ASP. NET Core MVC controllers.
    • Action for all ASP. NET MVC and Web API controllers.

If you need to disable authentication, review the "Disable Authentication" subsection.

Using data annotations

The ABP supports the data annotation feature, assuming that we are developing a task application service that creates a task and requires an input as follows:

 Public class createtaskinput{    publicintgetset;}    [Required]      Public string Get Set ; }}

Here the description attribute is marked as Required,assingedpersonid is optional, There are many features in the System.ComponentModel.DataAnnotations namespace, such as MaxLength, Minlenggth, regularexpression ... )。 The following is the implementation of the Task app service:

 Public classtaskappservice:itaskappservice{Private ReadOnlyitaskrepository _taskrepository; Private ReadOnlyipersonrepository _personrepository;  PublicTaskappservice (itaskrepository taskrepository, ipersonrepository personrepository) {_taskRepository =taskrepository; _personrepository=personrepository; }     Public voidcreatetask (createtaskinput input) {varTask =NewTask {Description =input.        Description}; if(input. Assignedpersonid.hasvalue) {task. Assignedperson=_personrepository.load (input.        Assignedpersonid.value);    } _taskrepository.insert (Task); }}

As you can see, the validation code is not written because the ABP automates validation. The ABP verifies that if the input is null, it throws Abpvalidationexception, so you do not need to write a null check. If any of the entered properties are not valid, it will also throw abpvalidationexception.

This mechanism is similar to the validation of ASP. NET MVC, but note that an app service class is not inherited from the controller, it is a simple class, and can even be used outside of a Web application.

Custom validation

If the data annotations are not enough for you to use, you can implement the Icustomvalidate interface as follows:

 Public classcreatetaskinput: icustomvalidate{ Public int? Assignedpersonid {Get;Set; }  Public BOOLSendemailtoassignedperson {Get;Set; } [Required] Public stringDescription {Get;Set; } Public   void  addvalidationerrors (Customvalidatationcontext context) {  if (Sendemailtoassignedperson && (!) Assignedpersonid.hasvalue | | Assignedpersonid.value <= 0)) {context. Results.add (new Validationresult ("Assignedpersonid must be set if Sendemailtoassignedperson is true! ")); }    }}

The Icustomvalidate interface defines the Addvalidationerrors method, and if there is a validation error, we must add the Validationresult object to the Context.results list. In the verification progress, if necessary, you can use the context. Iocresolver to parse dependencies.

The Ivalidatableobject interface is supported in addition to ICUSTOMVALIDATE,ABP. You can also implement it to perform additional custom validation. If you implement both interfaces at the same time, both will be called.

disabling validation

For automatic validation classes (see the Introduction section), you can use these features to control validation:

    • Disablevalidation Features: You can disable validation on a DTO class, method, or property.
    • Enablevalidation features: In a class that is disabled for validation, you can use this feature on methods to make input validation of the current method available.

Normalization

Sometimes we need to perform an extra action to defragment the DTO parameters after validation. The ABP defines the Ishouldnormailize interface, which contains the normalize method, and if you implement this interface, the normalize method is called after validation (before the method is called). Suppose we need to get the sort direction from the DTO (ascending, descending), if not provided, we want to set a default value:

 Public classgettasksinput: ishouldnormalize{ Public stringsorting {Get;Set; } Public   void  Normalize () {  if (string. Isnullorwhitespace (sorting)) {Sorting = "Name ASC" ; }    }}

<<ABP framework >> Validating data transfer objects

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.