出處:http://www.cnblogs.com/liuzhendong/p/4233380.html
讓Asp.Net WebAPI支持OData后,就能支持在url中直接輸入排序,過濾條件了。
一.創建Asp.Net WebAPI項目:


二.使用NuGet安裝Asp.Net WebAPI 2.2和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 = 0,
Filter = 1,
Expand = 2,
Select = 4,
OrderBy = 8,
Top = 16,
Skip = 32,
InlineCount = 64,
Supported = 127,
Format = 128,
SkipToken = 256,
All = 511,
}
五.運行示例:
http://localhost:port/api/ProjectManagent?$top=2&$filter=id lt 10&$orderby=id desc
表示返回id小於10,並按id倒序的前2條數據。
這看起來並不難,但好處是,它們都不需要寫任何代碼,也不用寫存儲過程,不用寫任何一個特別的邏輯去支持這些功能,全部都由OData框架來提供的。
也就是說,用了OData,為搜索、過濾、分頁的時候提供了一個很省事的選項。
六.代碼下載:
packages和bin目錄太大無法上傳,只把項目代碼打了個包。

