asp.net-core - ASPNET Core 3.x - Appending data to all API responses
问题描述
I've been googling for past 3 hours and I couldn't find anything helpful. I'm trying to transform all my requests to a specific RESTful standard.
Right now, each and every controller returns data in this format:
[
{
"id": 3,
"title": "Test",
"content": "Content Test",
"userId": 1,
"user": null,
"categoryId": null,
"category": null,
"comments": null,
"tags": null,
"createdOn": null,
"updatedOn": null
}
]
What I want is to wrap all of these responses in a container, that also consists of metadata - as seen below:
{
"statusCode": 200,
"statusMessage": "success",
"meta":
{
"count": 1,
"total": 1,
"pagination":
{
"page": 1,
"pages": 1,
"limit": 20
},
"filters": [],
"sorters": []
},
"data":
{
[
{
"id": 3,
"title": "Test",
"content": "Content Test",
"userId": 1,
"user": null,
"categoryId": null,
"category": null,
"comments": null,
"tags": null,
"createdOn": null,
"updatedOn": null
}
]
}
}
Is the proper approach to just make a class called ResponseContainer and make all controllers return it? Because I feel like that's a viable solution.
解决方案
在我的一个项目中,我使用了一个通用类作为响应,例如MyApiResponse<T>
. 此类包含元数据的属性,例如响应的 HttpStatusCode、错误消息等。它们是在每个响应时设置的。
在这堂课中,我有一个List<T>
叫做Data
.
每个 API 方法都返回MyApiResponse<T>
T 是具体数据类的位置。例如,它可能是MyApiResponse<Weather>
存储.Data
List<Weather
我也肯定会在我的下一个 API 项目中使用这种方法。
推荐阅读
- java - 如何替换已存档的 cucumber-jvm-parallel-plugin,以便为 Cucumber 自动生成跑步者
- php - 如何使用最新的 php 版本创建 laravel 项目?
- android - 如何在材料日历视图中设置选定日期
- java - Spring、hibernate基于不同数据库的类型映射
- sql - 将 SQL 查询结果保存到表中
- stackblitz - 为什么我收到此错误 (new Set(...)).slice is not a function?
- r - 用于多元回归的深度神经网络
- python - 使用 loc 命令替换值
- c# - 如何将文本输出到文本框?
- c++ - 如何删除向量中的元素
通过一个参考 for 循环