使用XmlSerializer进行数据分页

本文关键字:数据 分页 XmlSerializer 使用 | 更新日期: 2023-09-27 18:04:26

我已经设法实现$inlinecount与WebApi。OData (v 4.0.0)使用ODataQueryOptions<T>PageResult<T>类,如下所示:

POCO
public class Poco
{
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; }
}
控制器

[ActionName("Default")]
public PageResult<Poco> Get(ODataQueryOptions<Poco> queryOptions)
{
    var data = new Poco[] { 
        new Poco() { id = 1, name = "one", type = "a" },
        new Poco() { id = 2, name = "two", type = "b" },
        new Poco() { id = 3, name = "three", type = "c" },
        new Poco() { id = 4, name = "four", type = "d" },
        new Poco() { id = 5, name = "five", type = "e" },
        new Poco() { id = 6, name = "six", type = "f" },
        new Poco() { id = 7, name = "seven", type = "g" },
        new Poco() { id = 8, name = "eight", type = "h" },
        new Poco() { id = 9, name = "nine", type = "i" }
    };
    var t = new ODataValidationSettings() { MaxTop = 2 };
    queryOptions.Validate(t);
    var s = new ODataQuerySettings() { PageSize = 1 };
    IQueryable results = queryOptions.ApplyTo(data.AsQueryable(), s);
    var next = Request.GetNextPageLink();
    var count = Request.GetInlineCount();
    return new System.Web.Http.OData.PageResult<Poco>(
        results as IEnumerable<Poco>, next, count);
}

当我从JSON切换到老式XmlSerializer时,我得到错误406。有人知道这是否可行吗?

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
GlobalConfiguration.Configuration.Formatters.Remove(
    GlobalConfiguration.Configuration.Formatters.JsonFormatter);

使用XmlSerializer进行数据分页

PageResult不能被XmlSerializer序列化,因为它没有一个公共的、无参数的构造函数。但是没有什么可以阻止您定义自己的类似类型,它确实具有公共的无参数构造函数。这应该很简单。我建议查看PageResult的源代码,并采用类似的方法。