首页 > 解决方案 > 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.

标签: asp.net-core

解决方案


在我的一个项目中,我使用了一个通用类作为响应,例如MyApiResponse<T>. 此类包含元数据的属性,例如响应的 HttpStatusCode、错误消息等。它们是在每个响应时设置的。

在这堂课中,我有一个List<T>叫做Data.

每个 API 方法都返回MyApiResponse<T>T 是具体数据类的位置。例如,它可能是MyApiResponse<Weather>存储.DataList<Weather

我也肯定会在我的下一个 API 项目中使用这种方法。


推荐阅读