c# – 忽略Web API OData v4 $count = true

我开始了一个新的web api项目,并使用了最新的OData库,但是我无法按照它在之前3.0版本的odota库中的方式工作.无论我尝试过什么,我总是回到json对象的数组,而不是它包含在一个对象中,该对象应该具有原始未过滤/已排序集合中项目总数的计数.

几乎所有其他工作都按预期工作,我可以使用$filter,$top,$skip和$orderby.我还没有尝试过其他任何事情.我还尝试返回一个硬编码的实体列表,而不是DbSet< Company>但这没有任何区别.

任何人都可以告诉我我需要做些什么才能让它发挥作用?贝娄是回购所需的所有代码,我只展示了令人尊敬的代码(至少我认为是相关的代码).如果还有什么我需要展示请问.

packages.config

<package id="Microsoft.AspNet.WebApi" version="5.2.3" />
<package id="Microsoft.AspNet.OData" version="6.0.0" />
<package id="Microsoft.OData.Core" version="7.0.0" />
<package id="Microsoft.OData.Edm" version="7.0.0" />

公司模式

public sealed class Company {
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public CompanyState State { get; set; } // a simple int enum
    public DateTime CreatedOn { get; set; }
}

WebApiConfig.cs

public static void Register(HttpConfiguration config) {
    config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
    config.MapODataServiceRoute("odata", "odata", GetModel());
}
public static IEdmModel GetModel() {
    var builder = new ODataConventionModelBuilder();
    builder.EnableLowerCamelCase();
    var companySet = builder.EntitySet<Model.Company>("Company").EntityType.HasKey(x => x.CompanyId);
    return builder.GetEdmModel();
}

CompanyController.cs

[ODataRoutePrefix("Company")]
public sealed class CompanyController : ApiController {
    private DbContext context;
    public CompanyController(DbContext context) {
        this.context = context;
    }

    [EnableQuery] // also tried with [EnableQuery(MaxNodeCount = 50, MaxTop = 100, PageSize = 100)]
    [ODataRoute]
    [HttpGet]
    public IHttpActionResult Get()
    {
        return Ok(context.Set<Company>());
    }
}

测试网址

http://localhost:35743/odata/Company/?$count=true&$top=3

结果

[{"companyId":2,"name":"Company 1","state":1,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":3,"name":"Mars","state":0,"createdOn":"2016-11-12T21:10:41"}
,{"companyId":4,"name":"Veronica","state":0,"createdOn":"2016-11-12T21:10:41"}]

预期成绩:

{  
  "@odata.context":"some local url",
  "@odata.count": 9,  
  "value": [{"companyId":2,"name":"Company 1","state":1,"createdOn":"2016-11-12T21:10:41"}
    ,{"companyId":3,"name":"Mars","state":0,"createdOn":"2016-11-12T21:10:41"}
    ,{"companyId":4,"name":"Veronica","state":0,"createdOn":"2016-11-12T21:10:41"}]
} 

最佳答案 我没有从正确的控制器类型继承,我应该继承自ODataController而不是ApiController.

public sealed class CompanyController : ODataController

这样做解决了我面临的问题和奇怪的副作用,就像不被忽视的属性一样.

点赞