让Asp.Net WebAPI支持OData查询,排序,过滤。

时间:2021-07-30 03:47:33

让Asp.Net WebAPI支持OData后,就能支持在url中直接输入排序,过滤条件了。

一.创建Asp.Net WebAPI项目:

让Asp.Net WebAPI支持OData查询,排序,过滤。

让Asp.Net WebAPI支持OData查询,排序,过滤。

二.使用NuGet安装Asp.Net WebAPI 2.2和OData包

让Asp.Net WebAPI支持OData查询,排序,过滤。

让Asp.Net WebAPI支持OData查询,排序,过滤。

三.修改WebAPIConfig.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Net.Configuration; namespace ProjectManagementWebAppV3
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); config.EnableQuerySupport(); }
}
}

主要添加红色粗体字:config.EnableQuerySupport();
这是存在于System.Web.Http.OData.dll里的一个静态扩展方法,表示在项目中启用OData查询。

四.修改ProjectManagementControler.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProjectManagementWebAppV3.Models;
using System.Web.Http.OData.Query;
using ProjectManagementWebAppV3.Utility;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; namespace ProjectManagementWebAppV3.Controllers
{
public class ProjectManagentController : ApiController
{
private static List<ProjectModel> projectList = null; static ProjectManagentController()
{
projectList = new List<ProjectModel>
{
new ProjectModel { id=1, ProjectName = "项目1", MileStones = "2013年1月开始,3月组装测试,6月功能测试,10月上线;" },
new ProjectModel { id=2, ProjectName = "项目2", MileStones = "2013年3月开始,6月组装测试,9月功能测试,12月上线;" },
new ProjectModel { id=3, ProjectName = "项目3", MileStones = "2013年7月开始,9月组装测试,11月功能测试,12月上线;" }
};
}
/// <summary>
/// 获取全部数据
/// </summary>
/// <returns></returns>
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public List<ProjectModel> Get()
{
return projectList;
}
}
}

主要在Get方法上增加红色粗体字的属性:[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]

从下表可以看到,AllowedQueryOptions枚举支持的操作符号列表:

    public enum AllowedQueryOptions
{
None = ,
Filter = ,
Expand = ,
Select = ,
OrderBy = ,
Top = ,
Skip = ,
InlineCount = ,
Supported = ,
Format = ,
SkipToken = ,
All = ,
}

五.运行示例:

表示返回id小于10,并按id倒序的前2条数据。

这看起来并不难,但好处是,它们都不需要写任何代码,也不用写存储过程,不用写任何一个特别的逻辑去支持这些功能,全部都由OData框架来提供的。

也就是说,用了OData,为搜索、过滤、分页的时候提供了一个很省事的选项。

六.代码下载:

packages和bin目录太大无法上传,只把项目代码打了个包。

代码下载