Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Wrap API responses in a standarized format

$
0
0

Good evening,

I'm not really up to date with ASP.NET Core 3.x and I would like to get an advice.

I'm trying to standarize resource API output to look like this:

	{"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
				}
			]
		}
	}

As opposed to:

[
    {"id": 3,"title": "Test","content": "Content Test","userId": 1,"user": null,"categoryId": null,"category": null,"comments": null,"tags": null,"createdOn": null,"updatedOn": null
    }
]

The approach I've currently applied and works (but I don't find that good) is:

  • I have 2 classes: Resource and ResourceCollection
  • I use generic T classes in it, where T is basically model I'm trying to return (like Article, Post etc.)
  • Return them in controllers as opposed to returning Post or List<Post>

    The result? It works - but I don't think it should be done that way, here's the code for ResourceCollection as Resource is pretty similar:
namespace NppService.Resources
{
    public class ResourceCollection<T> where T : class
    {
        public List<T> Data { get; set; }

        public int Count => Data.Count;

        public int Total { get; set; }

        public ResourceCollection(List<T> data, DbContext context = null)
        {
            Data = data;

            if (context == null)
                return;

            Total = context.Set<T>().Count();
        }
    }
}

Thank you in advance for any advices.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>