使用 AspNetCore.OData 分页 - 响应中缺少 @odata 属性

Pagination with AspNetCore.OData - missing @odata properties in response

我正在尝试使用 asp.net core 2.2 和 Microsoft.AspNetCore.OData 7.1.0 实现分页,配置如下:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOData();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMvc(b =>
        {
            b.EnableDependencyInjection();
        });
    }
}

为此我有一个测试控制器:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    [EnableQuery(PageSize = 5)]
    public IQueryable<int> Get()
    {
        return new int[] { 1,2,3,4,5,6,7,8,9,10 }.AsQueryable();
    }
}

调用端点时,我希望得到如下响应:

{  
  "@odata.context":...,
  "value":[1,2,3,4,5],
  "@odata.nextLink":...  
}

但我只得到:

[1,2,3,4,5]

那么如何获得这些额外的@odata 属性?

我终于知道怎么做了。

首先,它不适用于原始类型,所以我不得不创建一个 ID 为 属性:

的强类型
public class Value
{
    public Value(int id)
    {
        Id = id;
    }

    public int Id { get; set; }
}

其次,我不得不从控制器中删除 ApiControllerRoute 属性。

public class ValuesController : ControllerBase
{
    [HttpGet]
    [EnableQuery(PageSize = 5)]
    public IQueryable<Value> Get()
    {
        return Enumerable.Range(1, 10).Select(i => new Value(i)).AsQueryable();
    }
}

最后注册 odata 端点:

ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Value>("Values");
app.UseOData("odata", "api", builder.GetEdmModel());