如何在ASP.NET Core中序列化包含对象的属性?

时间:2019-05-01 20:56:53

标签: c# json asp.net-core

我正在Microsoft上关注官方ASP.NET Core 2.2 paging example

在这里,我要添加一个PaginatedList.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace BlatantlyCopiedCode
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            this.AddRange(items);
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }

        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }
}

并将其添加到我的EF对象Merge

[HttpGet("[action]")]
public async Task<PaginatedList<Merge>> Index(int? pageNumber)
{
    var merges = context.Merges;

    int pageSize = 20;
    return await PaginatedList<Merge>.CreateAsync(merges.AsNoTracking(), pageNumber ?? 1, pageSize);
}

在控制器中将结果序列化为JSON时,PaginatedList<T>中的属性不会被序列化,只有List<Merge>会被序列化。如何强制PaginatedList<T>中的属性显示在生成的JSON中?

1 个答案:

答案 0 :(得分:2)

原因是它继承了List<T>,将结果限制在列表中。将代码修改为以下内容

public class PaginatedList<T> //: List<T>
{
    public int PageIndex { get; private set; }
    public int TotalPages { get; private set; }

    public List<T> Items { get; set; }

    public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);

        this.Items = new List<T>();
        this.Items.AddRange(items);
    }
    //...
 }