AspNet WebApi OData 学习
OData好处:通过OData,我们采取不同的方法。取代创建客户端签名和参数,我们问了如下的问题:“如果你将数据集作为源处理,并为最频繁使用的操作定义模式,像查 询、分页、排序、新建、删除和更新,服务接口因该是什么样子的?” 这也就导致OData的创建。OData解决了上面提到的关键服务设计挑战。
由于Visual Studio 2012里面的 AspNet WebApi 2 OData 中的 AspNet WebApi Client 5.0 依赖于 .Net Framework 4.5 框架,
所以只能去下载,.Net Framework 4.0 版本的 AspNet WebApi OData
AspNet WebApi OData 版本下载地址:https://www.nuget.org/packages/Microsoft.AspNet.WebApi.OData.zh-Hans/4.0.30506
$filter 用法:
Return all products with category equal to “Toys”. https://localhost/Products?$filter=Category eq 'Toys'
Return all products with price less than 10. https://localhost/Products?$filter=Price lt 10
Logical operators: Return all products where price >= 5 and price <= 15. https://localhost/Products?$filter=Price ge 5 and Price le 15
String functions: Return all products with “zz” in the name. https://localhost/Products?$filter=substringof('zz',Name)
Date functions: Return all products with ReleaseDate after 2005. https://localhost/Products?$filter=year(ReleaseDate) gt 2005
$orderby 用法:
Sort by price. https://localhost/Products?$orderby=Price
Sort by price in descending order (highest to lowest). https://localhost/Products?$orderby=Price desc
Sort by category, then sort by price in descending order within categories. https://localhost/odata/Products?$orderby=Category,Price desc
PageSize 用法:
[Queryable(PageSize=10)]
public IQueryable<Product> Get()
{
return products.AsQueryable();
}
客户端点击链接筛选到下一页,为了让客户端得到页码,我们必须求出结果集,这个客户端可以使用$inlinecount的一个叫“allpages”的参数,来得到总条数。
这个“allpages”值,就是服务端包含结果集的总数,响应告诉给客户端:
{
"odata.metadata":"https://localhost/$metadata#Products",
"odata.count":"50",
"value":[
{ "ID":1,"Name":"Hat","Price":"15","Category":"Apparel" },
{ "ID":2,"Name":"Socks","Price":"5","Category":"Apparel" },
]
}
//此方法,是用来处理分页数据查询,过滤,我们可以很方便灵活的去在客户端做处理。
public PageResult<Product> Get(ODataQueryOptions<Product> options)
{
ODataQuerySettings settings = new ODataQuerySettings()
{
PageSize = 5
};
IQueryable results = options.ApplyTo(_products.AsQueryable(), settings);
return new PageResult<Product>(
results as IEnumerable<Product>,
Request.GetNextPageLink(),
Request.GetInlineCount());
}
这里是一个返回Json的例子:
{
"Items": [{"ID":1,"Name":"Hat","Price":"15","Category":"Apparel"},
{"ID":2,"Name":"Socks","Price":"5","Category":"Apparel"},// Others not shown],
"NextPageLink" :"https://localhost/api/values?$inlinecount=allpages&$skip=10",
"Count": 50
}
推荐阅读
-
dotnet core webapi 开发学习 (1)
-
我的WebAPI学习(一)------ DOM元素的获取以及事件的基本用法
-
路由其实也可以很简单-------Asp.net WebAPI学习笔记(一)
-
AspNet WebApi OData 学习
-
Asp.net 学习记录(一)使用asp.net 构建webAPI接口
-
[转]Composite Keys With WebApi OData
-
webAPi OData的使用
-
.net core webapi +ddd(领域驱动)+nlog配置+swagger配置 学习笔记(1)
-
AspNet WebApi OData 学习
-
Asp.net 学习记录(一)使用asp.net 构建webAPI接口