什么是数据传输对象?

在MVC模型类DTO,如果不是什么区别,我们需要两者吗?


当前回答

所有功劳都归里克-安德森所有

生产应用程序通常限制使用模型子集输入和返回的数据。这背后有很多原因,安全是一个主要原因。模型的子集通常被称为数据传输对象(DTO)、输入模型或视图模型。

DTO可用于:

防止over-posting。 隐藏客户端不应该查看的属性。 为了减少有效负载大小,省略一些属性。 扁平化包含嵌套对象的对象图。 扁平化的对象图对客户来说更方便。

DTO方法的实际实现,由rick - anderson在微软Web api最佳教程和实践中使用c#和asp.net Core 5:

其他回答

数据传输对象(DTO)描述了“承载数据的对象” (维基百科)或“用于封装数据的对象”, 并将它从应用程序的一个子系统发送到另一个子系统”(堆栈溢出 答案)。

To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.

一些程序员使用DTO来区分将通过API传递的最终对象数据。它基本上是端点的有效载荷对象。比如,你可以将你传递给服务器的联系人表单值对象命名为contactFormDto或contactFromPayload,然后你或任何其他程序员都知道你在那个对象中拥有的是数据的最终形状,它将通过网络传播。

所有功劳都归里克-安德森所有

生产应用程序通常限制使用模型子集输入和返回的数据。这背后有很多原因,安全是一个主要原因。模型的子集通常被称为数据传输对象(DTO)、输入模型或视图模型。

DTO可用于:

防止over-posting。 隐藏客户端不应该查看的属性。 为了减少有效负载大小,省略一些属性。 扁平化包含嵌套对象的对象图。 扁平化的对象图对客户来说更方便。

DTO方法的实际实现,由rick - anderson在微软Web api最佳教程和实践中使用c#和asp.net Core 5:

我会把DTO解释给我的孩子

我的儿子,数据传输对象(又名DTO) **用于封装我们从一个端点发送到另一个端点的数据。 使用DTO为系统中的端点定义输入和输出接口 在这种情况下,可以将系统看作端点的集合。端点可以是任何相互通信的东西(移动应用程序,web应用程序,后端API)。