I’m working with JSON API .NET Core library to build my REST API. I need to include a record count field in the metadata section of my responses but I can’t figure out how to do it.
Here’s my current base entity implementation:
public class EntityBase : Identifiable, IHasMeta
{
public string Author { get; set; }
public string Editor { get; set; }
public Dictionary<string, object> GetMeta(IJsonApiContext context)
{
return new Dictionary<string, object> {
{ "license", "MIT License" },
{ "contributors", new string[] { "John", "Jane" } }
};
}
}
I want to add something like total-records or similar count information to this metadata. The documentation doesn’t seem to cover this specific scenario. Has anyone managed to implement this successfully? What’s the best approach to get the total count of records and include it in the meta response?
I had good luck with a custom document builder approach. Skip the entity-level handling and extend the DocumentBuilder class instead - override the Build method to add pagination metadata at the document level. This way you get the full query context before any filtering kicks in. Run a count query against your DbSet with the same filters (minus pagination params), then inject that into your JSON API response’s top-level meta section. Your entities stay clean and the document-level metadata handles the cross-cutting stuff like total counts. Just register your custom document builder in the DI container and the serialization pipeline will pick it up automatically.
I solved this by creating a custom meta provider that gets injected into my controllers. Here’s the trick: override GetRelationshipAsync in your resource service and modify the TopLevelLinks property. You’ll need to grab the total count through your repository layer before pagination happens, then store it in HttpContext items. Your IHasMeta implementation can pull it from there and add the count to the metadata dictionary. The critical part - get that total count before any Skip/Take operations hit your queryable. Otherwise you’ll just get the page size back. Cache this value per request since the meta method gets called multiple times during serialization.
u should create a custom resource service that overrides GetAsync. Calculate your record count there and add it to the meta before returning. i faced the same issue last month, it worked for me but had to check the source code for the right way.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.