Search code examples
.netasp.net-corejson-api

Add total-count in meta data using JSON API .Net Core


I'm using the JSON API .Net Core to create .Net API. How to add total-count in meta-data? enter image description here

public class BaseEntity : Identifiable, IHasMeta
    {

        public string CreatedBy { get; set; }

        public string ModifiedBy { get; set; }

        public Dictionary<string, object> GetMeta(IJsonApiContext context)
        {
            return new Dictionary<string, object> {
            { "copyright", "Copyright Croos" },
            { "authors", new string[] { "Croos" } }
        };
        }
    }

There is nothing about it in the document. Thanks.


Solution

  • Firstly, enable the IncludeTotalRecordCount options:

    public void ConfigureServices(IServiceCollection services)
    {
        ... other services
    
        services.AddJsonApi<AppDbContext>(o =>{
            o.IncludeTotalRecordCount = true;
        });
    }
    

    And now we can retrieve the total records by context.PageManager.TotalRecords :

    public class Person : Identifiable, IHasMeta
    {
        [Attr("name")]
        public string Name { get; set; }
    
        public Dictionary<string, object> GetMeta(IJsonApiContext context)
        {
            return new Dictionary<string, object> {
                { "total-records", context.PageManager.TotalRecords },
            };
        }
    }
    

    A working demo :

    enter image description here