I use ASP. Webapi to support the OData protocol for paging operations (second article)

Source: Internet
Author: User


While reading this article, I think you have read the first article. • It is also possible that, like me, it is now using ASP. NET Webapi to work for us. It might be a service paged query interface, or it might be something else, and there are some minor problems. If there is a problem, let's solve the problem. Long live the yard, long live, million long live! )


In other words, the ASP. NET MVC WebAPI is built on the basis of ASP. All requests are handled in accordance with MVC's routing rules, and for the interception and processing of requests, they can be inherited by custom

System.Web.Http.Filters.ActionFilterAttribute

The arbitrary tag class, and then rewrite the 4 methods inside onactionexecuted,onactionexecutedasync,onactionexecuting

Onactionexecutingasync to enable interception, filtering, and so on for requests. The global registration is finally done through the action tag, or through Global.asax. You can implement the request interception and custom logic management of MVC.


Look at the truth of it. Defined as follows:

Public abstract class Actionfilterattribute:filterattribute, Iactionfilter, IFilter

As you can see, it is an abstract class that inherits from FilterAttribute and implements the Iactionfilter,ifilter two interfaces at the same time. (no more to the inside, interested in you can see for yourself, you can also complete the technical Book of ASP.) )


The following is a partial implementation of the core code (refer to: System.Web.OData project source Enablequeryattribute object definition)

        /// <summary>    ///  The tag action returns the result as a paging data object. The     /// action itself must return iqueryable&lt; 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 settings         private ODataValidationSettings _validationSettings;         private string _allowedOrderByProperties;         // query settings         private 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 static method, reference: System.Web.OData.Extension queryableextensions     //  for querying paging data and the total number of data records.     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 Management Assistant Helper    internal 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 (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;    }            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 collections                 Type[]  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;         }    }


The next article will describe how to use it, as well as items that need attention and project source code.

This article is from the "idiot" blog, make sure to keep this source http://hotboy.blog.51cto.com/8826994/1651277

I use ASP. Webapi to support the OData protocol for paging operations (second article)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.