Introduction to validation

Inputs of an application should be validated first. This input can be sent by user or another application. In a web application, validation is usually implemented twice: in client and in the server. Client-side validation is implemented mostly for user experience. It's better to check a form first in the client and show invalid fields to the user. But, server-side validation is more critical and unavoidable.

应用程序的输入应该首先验证。此输入可以由用户或其他应用程序发送。在Web应用程序中,验证通常实现两次:客户端和服务器端。客户端验证主要用于用户体验。最好在客户端检查表单,并向用户显示无效字段。但是,服务器端验证更为关键和不可避免。

Server side validation is generally implemented in application services or controllers (in general, all services get data from presentation layer). An application service method should first check (validate) input and then use it. ASP.NET Boilerplate provides a good infrastructure to automatically validate all inputs of an application for;

服务器端验证通常在应用程序服务或控制器中实现(一般来说,所有服务都从表示层获取数据)。应用程序服务方法应该首先检查(验证)输入然后使用它。ASP.NET样板提供良好的基础设施来自动验证所有输入的应用;

See Disabling Validation section to disable validation if needed.

如果需要,请查看禁用验证部分禁用验证。

Using data annotations(使用数据注释)

ASP.NET Boilerplate supports data annotation attributes. Assume that we're developing a Task application service that is used to create a task and gets an input as shown below:

ASP.NET样板支持数据注解属性。假设我们正在开发一个任务应用程序服务,该服务用于创建任务并获取如下所示的输入:

public class CreateTaskInput
{
public int? AssignedPersonId { get; set; } [Required]
public string Description { get; set; }
}

Here, Description property is marked as Required. AssignedPersonId is optional. There are also many attributes (like MaxLength, MinLength, RegularExpression...) in System.ComponentModel.DataAnnotationsnamespace. See Task application service implementation:

这里,Description属性被标记为所需。assignedpersonid是可选的。也有许多属性(如MaxLength,minLength,正则表达式在System.ComponentModel.DataAnnotationsnamespace…)。查看任务应用程序服务实现:

public class TaskAppService : ITaskAppService
{
private readonly ITaskRepository _taskRepository;
private readonly IPersonRepository _personRepository; public TaskAppService(ITaskRepository taskRepository, IPersonRepository personRepository)
{
_taskRepository = taskRepository;
_personRepository = personRepository;
} public void CreateTask(CreateTaskInput input)
{
var task = new Task { Description = input.Description }; if (input.AssignedPersonId.HasValue)
{
task.AssignedPerson = _personRepository.Load(input.AssignedPersonId.Value);
} _taskRepository.Insert(task);
}
}

As you see, no validation code is written since ASP.NET Boilerplate does it automatically. ASP.NET Boilerplate also checks if input is null and throws AbpValidationException if so. So, you don't have to write null-check code (guard clause). It also throws AbpValidationException if any of the input properties are invalid.

正如你看到的,没有验证码可写,因为ASP.NET样板是自动写入的。ASP.NET样板检查是否输入是无效的,如果无效则抛出abpvalidationexception。因此,您不必编写null检查码(保护子句)。如果任何输入属性无效它会抛出abpvalidationexception。

This machanism is similar to ASP.NET MVC's validation but notice that an application service class is not derived from Controller, it's a plain class and can work even out of a web application.

这种机制是类似ASP.NET MVC的验证而注意到应用服务类不是来自控制器,它是一个普通班,甚至可以从一个Web应用程序的工作

Custom Validation(自定义验证)

If data annotations are not sufficient for your case, you can implement ICustomValidate interface as shown below:

如果数据注释不够满足你的情况,你可以实现icustomvalidate 接口如下图所示:

public class CreateTaskInput : ICustomValidate
{
public int? AssignedPersonId { get; set; } public bool SendEmailToAssignedPerson { get; set; } [Required]
public string Description { 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!"));
}
}
}

ICustomValidate interface declares AddValidationErrors method to be implemented. We must add ValidationResult objects to context.Results list if there are validation errors. You can also use context.IocResolver toresolve dependencies if needed in validation progress.

icustomvalidate 接口揭露 addvalidationerrors方法被执行。我们必须在上下文中加上ValidationResult对象。如果验证错误。你也可以使用context.iocresolver 如果在验证中需要。

In addition to ICustomValidate, ABP also supports .NET's standard IValidatableObject interface. You can also implement it to perform additional custom validations. If you implement both interfaces, both of them will be called.

除了icustomvalidate,ABP也支持.NET的标准ivalidatableobject接口。您也可以执行它执行其他自定义验证。如果实现这两个接口,它们都将被调用。

Disabling Validation(禁用验证)

For automatically validated classes (see Introduction section), you can use these attributes to control validation:

对于自动验证类(参见导言部分),您可以使用这些属性来控制验证:

  • DisableValidation attribute can be used for classes, methods or properties of DTOs to disable validation.
  • disablevalidation属性可以用于类、方法或属性的DTOS禁用验证。
  • EnableValidation attribute can only be used to enable validation for a method, if it's disabled for the containing class.
  • enablevalidation属性只能用于使一个方法验证,如果该类被禁用。

Normalization(标准化)

We may need to perform an extra operation to arrange DTO parameters after validation. ASP.NET Boilerplate defines IShouldNormalize interface that has Normalize method for that. If you implement this interface, Normalize method is called just after validation (and just before method call). Assume that our DTO gets a Sorting direction. If it's not supplied, we want to set a default sorting:

我们可能需要执行额外的操作安排DTO参数后验证。ASP.NET的模板定义ishouldnormalize接口,有规范的方法。如果实现此接口,则在验证之后(调用方法调用之前)调用标准化方法。假设我们的DTO获取排序方向。如果没有提供,我们要设置默认排序:

public class GetTasksInput : IShouldNormalize
{
public string Sorting { get; set; } public void Normalize()
{
if (string.IsNullOrWhiteSpace(Sorting))
{
Sorting = "Name ASC";
}
}
}

ABP框架系列之五十二:(Validating-Data-Transfer-Objects-验证数据传输对象)的更多相关文章

  1. ABP框架系列之五十四:(XSRF-CSRF-Protection-跨站请求伪造保护)

    Introduction "Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a maliciou ...

  2. ABP框架系列之十二:(Audit-Logging-审计日志)

    Introduction Wikipedia: "An audit trail (also called audit log) is a security-relevant chronolo ...

  3. ABP框架系列之三十二:(Logging-登录)

    Server Side(服务端) ASP.NET Boilerplate uses Castle Windsor's logging facility. It can work with differ ...

  4. ABP框架系列之四十二:(Object-To-Object-Mapping-对象映射)

    Introduction It's a common to map a similar object to another object. It's also tedious and repeatin ...

  5. ABP框架系列之五十:(Swagger-UI-集成)

    Introduction From it's web site: "....with a Swagger-enabled API, you get interactive documenta ...

  6. ABP框架系列之三十九:(NLayer-Architecture-多层架构)

    Introduction Layering of an application's codebase is a widely accepted technique to help reduce com ...

  7. ABP框架系列之十八:(Data-Transfer-Objects-数据转换对象)

    Data Transfer Objects are used to transfer data between Application Layer and Presentation Layer. 数据 ...

  8. ABP框架系列之三十四:(Multi-Tenancy-多租户)

    What Is Multi Tenancy? "Software Multitenancy refers to a software architecture in which a sing ...

  9. ABP框架系列之十:(Application-Services-应用服务)

    Application Services are used to expose domain logic to the presentation layer. An Application Servi ...

随机推荐

  1. 知识点:Mysql 基本用法之函数

    函数 MySQL中提供了许多内置函数 例如: sql 内置函数: 一.数学函数 ROUND(x,y) 返回参数x的四舍五入的有y位小数的值 RAND() 返回0到1内的随机值,可以通过提供一个参数(种 ...

  2. HDFS知识点总结

    学习完Hadoop权威指南有一段时间了,现在再回顾和总结一下HDFS的知识点. 1.HDFS的设计 HDFS是什么:HDFS即Hadoop分布式文件系统(Hadoop Distributed File ...

  3. 机器学习简要笔记(五)——Logistic Regression(逻辑回归)

    1.Logistic回归的本质 逻辑回归是假设数据服从伯努利分布,通过极大似然函数的方法,运用梯度上升/下降法来求解参数,从而实现数据的二分类. 1.1.逻辑回归的基本假设 ①伯努利分布:以抛硬币为例 ...

  4. import 搜索路径

    来源 http://www.runoob.com/python/python-mysql.html 搜索路径 当你导入一个模块,Python 解析器对模块位置的搜索顺序是: 1.当前目录 2.如果不在 ...

  5. vue+窗格切换+田字+dicom显示_01

    环境:vue+webpack+cornerstone ide:vs code 需求:窗格设置+拼图设置 1.点击左边第一个窗格或者默认显示. 2.点击第二个也同理显示,以此类推 3.选择左边的窗格之后 ...

  6. linux tail 命令详解

    linux ---tail命令 linux中tail命令---用于查看文件内容 最基本的是cat.more和less. 1. 如果你只想看文件的前5行,可以使用head命令,如: head -5 /e ...

  7. 从零开始实现RPC框架 - RPC原理及实现

    最近被人问到RPC相关的东西~突然发现还是有很多原理没有清楚,所以要好好系统的学习一下RPC以及它的原理 先大致了解一下RPC的大概,原文:https://blog.csdn.net/top_code ...

  8. spring boot 之 错误:SpelEvaluationException: EL1008E: Property or field 'timestamp' cannot be found on object of type 'java.util.HashMap'

    这个错误我也见过很多次了,今天终于理解了其出现的原因. 错误是这样的: 2017-11-23 18:05:39.504 ERROR 4092 --- [nio-8080-exec-3] o.a.c.c ...

  9. jQuery入门基础(动画效果)

    一.隐藏显示 1.show()--显示隐藏的被选择元素 例:$(selector).show(speed,callback); 2.hide()--隐藏被选元素的内容 例:$(selector).hi ...

  10. python——列表入门

    学习列表先分析一段程序: list = ['zx', 'xkd', 1997, 2018] list1=list+[1,2,3]#列表拼接 list2=[list,list1] print('嵌套的列 ...