After adding the OData feature to ASP. NET Webapi, you can support the direct input of sorting in the URL and filter the conditions.
I. Modification of WebAPIConfig.cs:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web.Http;usingSystem.Net.Http.Formatting;usingSystem.Net.Configuration;namespaceprojectmanagementwebappv3{ Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Web API RoutesCONFIG. 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 (); } }}
The main addition is red bold word:config. Enablequerysupport ();
This is a static extension method that exists in System.Web.Http.OData.dll, which means that OData queries are enabled in the project.
Two. Modify ProjectManagementControler.cs:
UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Net;UsingSystem.Net.Http;UsingSystem.Web.Http;UsingProjectmanagementwebappv3.models;using System.Web.Http.OData.Query; Usingprojectmanagementwebappv3.utility;UsingSystem.Data;UsingSystem.Data.SqlClient;UsingSystem.Configuration;Namespaceprojectmanagementwebappv3.controllers{PublicClassProjectmanagentcontroller:apicontroller {Privatestatic List<projectmodel> projectlist =Null;StaticProjectmanagentcontroller () {projectlist =New list<projectmodel>{New Projectmodel {id=1, ProjectName ="Item 1", milestones ="January 2013 start, March Assembly test, June function test, October on line;"},New Projectmodel {id=2, ProjectName ="Item 2", milestones ="March 2013 start, June Assembly test, September function test, December on line;"},New Projectmodel {id=3, ProjectName ="Item 3", milestones = " July 2013 start, September Assembly test, November Functional test, December on-line; "}}; } ///<summary> / get all data ///</ summary> ///<returns></returns> [queryable (allowedqueryoptions = Allowedqueryoptions.all)] Span style= "color: #0000ff;" >public list<projectmodel> Get () {return Projectlist; } }}
The properties of Red bold characters are added mainly on the Get method:[queryable (allowedqueryoptions = allowedqueryoptions.all)]
Three. Run the example:
Http://localhost:port/api/ProjectManagent? $top =2& $filter =id lt 10& $orderby =id Desc
Four. Code Download:
Packages and Bin directory too large to upload, only the project code to a package.
Code download
ASP. Webapi Add OData feature, support query, sort, filter.