我使用Asp.net MVC WebAPI支持OData协议进行分页操作的笔记(第二篇)
在阅读这篇文章的时候,我想你已经看完第一篇文章啦·也有可能跟我一样,现在正在使用它Asp.net WebAPI为我们干活儿。可能是服务分页查询接口,也可能是其它操作,遇到了一些小问题。有问题,那咱就来解决问题吧!(码农万岁,万岁,万万岁!)
扯两句,Asp.net MVC WebAPI,是建立在Asp.net MVC基础上的。所有的请求处理,都遵循MVC的路由规则,对于请求的拦截与处理,都可以通过自定义继承自
System.Web.Http.Filters.ActionFilterAttribute
的任意标记类,然后重写里面的4个方法OnActionExecuted,OnActionExecutedAsync,OnActionExecuting
OnActionExecutingAsync 来实现对请求的拦截,过滤等等。最后通过Action标记,或者通 Global.asax 中进行全局注册。就可以实现MVC的请求拦截与自定义的逻辑管理了。
看看它的庐山真面目。定义如下:
public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IFilter
可以看到,它是一个抽象类,继承自FilterAttribute,同时实现了IActionFilter,IFilter两个接口。(不再往里面扒了,有兴趣你可以自己瞧瞧,也可以整本ASP.NET MVC的技术书看看。)
下面是部分核心代码的实现(参考:System.Web.OData项目源码的EnableQueryAttribute对象定义)
/// <summary>/// 标记Action返回结果为分页数据对象。/// Action本身必须返回IQueryable<T>/// -------------------------------------/// add by hotboy 2015-5-14 11:32:27/// </summary>[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]public class ODataPagedAttribute : System.Web.Http.Filters.ActionFilterAttribute{private const char CommaSeparator = ',';private const string PageSizeKey = "$pagesize";private const int DefaultPageSize = 20;// validation settingsprivate ODataValidationSettings _validationSettings;private string _allowedOrderByProperties;// query settingsprivate ODataQuerySettings _querySettings;/// <summary>/// Enables a controller action to support OData query parameters./// </summary>public ODataPagedAttribute(){_validationSettings = new ODataValidationSettings();_querySettings = new ODataQuerySettings();}//... more than code here ....// }//// IQeruyable静态方法,参考:System.Web.OData.Extension的QueryableExtensions// 用于查询分页数据以及数据记录总数。public class QueryableExtensions{private static MethodInfo _limitResultsGenericMethod = typeof(QueryableExtensions).GetMethod("LimitResults");internal static IQueryable LimitResults(IQueryable queryable, int limit, out bool resultsLimited, out int total){MethodInfo genericMethod = _limitResultsGenericMethod.MakeGenericMethod(queryable.ElementType);object[] args = new object[] { queryable, limit, null, null };IQueryable results = genericMethod.Invoke(null, args) as IQueryable;resultsLimited = (bool)args[2];total = (int)args[3];return results;}/// <summary>/// Limits the query results to a maximum number of results./// </summary>/// <typeparam name="T">The entity CLR type</typeparam>/// <param name="queryable">The queryable to limit.</param>/// <param name="limit">The query result limit.</param>/// <param name="resultsLimited"><c>true</c> if the query results were limited; <c>false</c> otherwise</param>/// <returns>The limited query results.</returns> public static IQueryable<T> LimitResults<T>(IQueryable<T> queryable, int limit, out bool resultsLimited, out int total){total = queryable.Count();TruncatedCollection<T> truncatedCollection = new TruncatedCollection<T>(queryable, limit);resultsLimited = truncatedCollection.IsTruncated;return truncatedCollection.AsQueryable();}}// Type管理辅助Helperinternal static class TypeHelper {internal static Type GetImplementedIEnumerableType(Type type){// get inner type from Task<T>if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>)){type = type.GetGenericArguments().First();}if (type.IsGenericType && type.IsInterface &&(type.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||type.GetGenericTypeDefinition() == typeof(IQueryable<>))){// special case the IEnumerable<T>return GetInnerGenericType(type);}else{// for the rest of interfaces and strongly Type collectionsType[] interfaces = type.GetInterfaces();foreach (Type interfaceType in interfaces){if (interfaceType.IsGenericType &&(interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||interfaceType.GetGenericTypeDefinition() == typeof(IQueryable<>))){// special case the IEnumerable<T>return GetInnerGenericType(interfaceType);}}}return null;}private static Type GetInnerGenericType(Type interfaceType){// Getting the type T definition if the returning type implements IEnumerable<T>Type[] parameterTypes = interfaceType.GetGenericArguments();if (parameterTypes.Length == 1){return parameterTypes[0];}return null;}}
下一篇文章,将介绍怎么样使用它,以及项目中需要注意事项与项目源代码下载地址。
转载于:https://blog.51cto.com/oceanho/1651277
我使用Asp.net MVC WebAPI支持OData协议进行分页操作的笔记(第二篇)相关推荐
- 我使用Asp.net MVC WebAPI支持OData协议进行分页操作的笔记(第一篇)
OData协议.多么牛B的技术. 传统的分页写习惯了,最近项目中,用到了 Asp.net WebAPI 2.0来做数据交互接口.至于为什么要使用WebAPI,我想只要是对OData协议有了解的朋友.只 ...
- asp.net mvc 正常支持Fckeditor编辑器
在接近下班的时候,快速的浏览了博客园的首页,被该贴"建站专家:让 MVC 支持 CuteEditor Using CuteEditor under MVC"中的话题"As ...
- 【转】.net异步性能测试(包括ASP.NET MVC WebAPI异步方法)
很久没有写博客了,今年做的产品公司这两天刚刚开了发布会,稍微清闲下来,想想我们做的产品还有没有性能优化空间,于是想到了.Net的异步可以优化性能,但到底能够提升多大的比例呢?恰好有一个朋友正在做各种语 ...
- ASP.NET MVC WebAPI 资源整理
注:这是收集给公司同事学习的资料,入门级别的. 使用ASP.Net WebAPI构建REST服务(一)--简单的示例 http://blog.csdn.net/mengzhengjie/article ...
- Asp.Net MVC WebAPI的创建与前台Jquery ajax后台HttpClient调用详解
1.什么是WebApi,它有什么用途? Web API是一个比较宽泛的概念.这里我们提到Web API特指ASP.NET MVC Web API.在新出的MVC中,增加了WebAPI,用于提供REST ...
- 请MVC5 WebApi2 支持OData协议查询
一.配置项 1.WebApiConfig.cs添加如下代码: // api 支持 cors允许Ajax发起跨域的请求(nuget 中搜索 ASP.NET Cross-Origin Support,然后 ...
- ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml)
我们都知道在使用WebApi的时候Controller会自动将Action的返回值自动进行各种序列化处理(序列化为json,xml等),但是如果Controller的自动序列化后的结果不是我们想要的该 ...
- Asp.net MVC WebApi Response AOP_se7en3_新浪博客
WebApi项目需要在输出Json时对Json进行编码处理.考虑使用MVC 的AOP 查阅文档需要HttpMessageHandle 新建类CryptDelegatingHandler public ...
- ASP.NET MVC WebAPI实现文件批量上传
工作中学习,学习中记录~~~~~~ 最下面附上demo 任务需求:需要做一个apI接口让C#的程序调用实现批量文件的上传. 难度: 没有做过通过API上传文件的...之前做过网站前后台上传. 首先当然 ...
最新文章
- silverlight 无法发布 如何灵活配置IP
- JavaScript中函数四种调用模式
- h1.1 hadoop简介
- Visual Studio Code 1.33 发布
- 空间谱专题09:阵列信号建模方法
- ROS学习笔记-使用C++类用以编程(以机器人语音交互为例)
- Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]
- python图片重命名 工具_python - 请问django如何给上传的图片重命名
- C/C++获取本地IP(适用于多种操作系统)
- python pip 安装
- System.Timers.Timer 与 System.Threading.Timer 小间隔
- 关于程序猿的六个问答题
- 11g oracle 客户端驱动_oracle odbc driver configuration(oracle 11g odbc驱动程序) 64位/32位
- 【老生谈算法】matlab遗传算法工具箱源码——遗传算法
- 文件上传之IIS—put漏洞
- 自动控制原理学习笔记--反馈控制系统的动态模型
- C#人事工资管理系统
- 程序员不能错过的20个学习网站
- Unix编程艺术:哲学基础
- 短除法(求最大公约数)