Web API 2 REST 服务高级数据过滤

Web API 2 REST Service Advanced Data Filtering

我的团队目前已经使用 .NET 的 Web API 2 平台实现了 REST API (JSON)。我们有一些有效的 URL,例如:

/api/schools 
/api/schools/5000 
/api/occupations 
/api/occupations/22

这里是我们的一些数据控制器代码:

public class OccupationsController : ApiController
{
    // /api/Occupations/1991
    public IHttpActionResult GetOccupation(int id)
    {
        var occupation = GetAllOccupations().FirstOrDefault((p) => p.OccupationID == id);
        if (occupation == null)
        {
            return NotFound();
        }
        return Ok(occupation);
    }
    // /api/occupations
    public IEnumerable<Occupation> GetAllOccupations()
    {
        var ctx = new TCOSDBEntities();
        return ctx.Occupations.OrderBy(occupation => occupation.Title);          
    }

}

我们现在正在引入数据过滤(基于用户复选框选择),我很好奇如何在我们现有的 API 中解决这个问题,或者我是否应该放弃 REST 进行过滤并尝试其他方法一起?

这是我们的复选框过滤机制: Checkbox UI

如何在我的 REST 服务和 DataController 方法中引入搜索参数?比如,我如何获得一个字段的范围过滤器(比如 Cost?)?我可以过滤多个字段,例如费用、学费等吗?

来自以上评论:

You should look into the oData implementation for Web API, there are a couple of MS NuGet packages you have to install. After that its mostly configuring what you want to expose, any restrictions you want to limit the callers to (like max page size), and the rest is done by the client by manipulating the URL to filter, page, sort, etc.

举个例子:

Url样本

这将检索列表中按名称排序的前 24 所学校,其中学生人数在 10 到 100 之间(含)

/odata/Schools/?$count=true&$top=24&$skip=0&$filter=(numberOfStudents ge 10 and numberOfStudents le 100)&$orderby=name desc

SchoolController.cs

using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;

[ODataRoutePrefix("Schools")]
public sealed class SchoolODataController : ODataController
{
    private DbContext _context; // your DbContext implementation, assume some DbSet<School> with the property name Schools

    public SchoolODataController(DbContext context)
    {
        _context = context;
    }

    [EnableQuery(MaxNodeCount = 200, MaxTop = 100, PageSize = 64 )]
    [ODataRoute]
    [HttpGet]
    public IHttpActionResult Get()
    {
        return Ok(_context.Schools);
    }
}

WebApiConfig.cs

using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // other code
        config.MapODataServiceRoute("odata", "odata", GetModel());
    }

    public static IEdmModel GetModel()
    {
        var builder = new ODataConventionModelBuilder();
        builder.EnableLowerCamelCase();
        var setOrders = builder.EntitySet<SchoolModel>("Schools").EntityType.HasKey(x => new { x.SchoolId });
        return builder.GetEdmModel();
    }
}

NuGet 包

Install-Package Microsoft.AspNet.OData
Install-Package Microsoft.OData.Core
Install-Package Microsoft.OData.Edm