[Boiled ASP. NET Web API2 methodology] (12-3) OData query, api2odata

Source: Internet
Author: User

[Boiled ASP. NET Web API2 methodology] (12-3) OData query, api2odata

Problem

How does a Web API support common OData system query items, such as $ select or $ filter.

 

Solution

To enable query items in the Web API, EnableQueryAttribute must be used on the Action.

If Action does not return a set but returns an instance of a single object, the caller can still use the $ expand and $ select query statements to achieve this purpose, we must wrap the returned object in SingleResult <T>. Examples of returned values of a set and a single object instance are shown in orders 12-7.

Listing 12-7. Enabling query statements on two routes

 1     public class PlayersController : ODataController 2  3     { 4  5         private readonly PlayersContext playersDbContext = new PlayersContext(); 6  7         [EnableQuery] 8  9         public IQueryable<Player> GetAllPlayers()10 11         {12 13             Return playersDbContext;14 15         }16 17         [EnableQuery]18 19         public SingleResult<Player> GetSinglePlayers(int key)20 21         {22 23             return SingleResult.Create(playersDbContext.Where(x => x.Id == key).AsQueryable());24 25         }26 27     }

 

Working Principle

The OData query option is defined in the OData specification. For example, the query string parameter controls the quantity and order of returned resources. ASP. NET Web APIs support almost all standard query items:

  • $ Expand: allows the information returned to the client to contain associated resources (navigation properties)
  • $ Select: Restrict returned attributes
  • $ Filter: filter resources exposed by Api
  • $ Count: obtains the total number of entities in the set.
  • $ Orderby: Specifies the sort key of the set.
  • $ Skip: Get the number of skipped Sets
  • $ Top: Limit the number of returned sets.
  • $ Format: Request-specific response format

The only query parameter that is not supported is $ search.

 

TipsYou can see the complete documentation addresses supported by OData 4.0: http://docs.oasis-open.org/OData/new-in-OData/v4.0/cn01/new-in-OData-v4.0-cn01.html

The query item is described by the ODataQueryOption class in ASP. NET Web API. The working method of EnableQueryAttribute is actually very simple. Because it is the Filter of Action, the OnActionExecuted method obtains the Action response and converts HttpContent to ObjectContent <T>. Then, the ODataQueryOptions instance is constructed based on the HttpRequest client parameters, and the corresponding response is returned to the client. If the response is a collection, you can respond to all the query items on the client. If the response is not a set, it will be packaged into SingleResult <T> through ObjectContent. In these cases, both $ expand and $ select are available.

You can also use ODataQueryOptions without using EnableQueryAttribute. It can accept the parameter of Action. This method is supported by customizing ODataQueryParameterBinding of the HttpParameterBinding type. You can also use the information in the ODataQueryOptions instance to manually perform related queries.

In Web APIs, we don't need to fully master OData to realize the convenience that query items bring to us. Even if it is not based on ODataCotrollers, as long as the EnableQueryAttribute label is used on the Action, we can still use some basic query items on the Web API, such as $ top, $ skip, and $ select.

 

Code demo

Use EnableQueryAttribute on the Controller Action, so that the request can use OData query items, such as List 12-7.

  • Host/Plays (1) $ select = Name, Team: uses the Player entity Id for filtering. Only two attributes, Name and Team, are returned. Response in this example, such as List 12-8.

 

Listing 12-8. Example of querying responses from OData Web APIs

{  "@OData.context":"http://localhost:43539/OData/$metadata#Players(Name,Team)/$entity","Name":"Name1","Team":"Team"} 
  • Host/Players? Skip = 1 & $ top = 2: Ignore the first object in the set, and then obtain two returned results from the remaining entities (it can be understood as the second page of data on the page, the size of each page is 2 ). Specific response, as shown in listing 12-9.

Listing 12-9. Example of querying responses from OData Web APIs

{  "@OData.context":"http://localhost:43539/OData/$metadata#Players","value":[    {      "Id":1,"Name":"Name1","Team":"Team"    },{      "Id":2,"Name":"Name11","Team":"Team"    }  ]}
  • Host/Players? $ Format = application/json; OData. metadata = full & $ filter = Team % 20eq % 20% 27Team2% 27: The request condition where you set the Team attribute value to Whales is returned in json format and contains all OData metadata, contains the type and navigation link. Specific response results, as shown in listing 12-10
{  "@OData.context":"http://localhost:43539/OData/$metadata#Players","value":[    {      "@OData.type":"#BoiledCode.WebApi.Recipe.ODataDemo.Models.Player","@OData.id":"http://localhost:43539/OData/Players(3)","@OData.editLink":"http://localhost:43539/OData/Players(3)","Id":3,"Name":"Name2","Team":"Team2"    },{      "@OData.type":"#BoiledCode.WebApi.Recipe.ODataDemo.Models.Player","@OData.id":"http://localhost:43539/OData/Players(4)","@OData.editLink":"http://localhost:43539/OData/Players(4)","Id":4,"Name":"Name21","Team":"Team2"    }  ]}

 

As mentioned above, we can use the ODataQueryOptions parameter in the Action Method to manually implement the query item. ODataQueryParameterBinding will help me complete the operation of passing objects to the Action, so that we can extract the OData-related query items in the Action.

Listing 12-11. Using ODataQueryOptions in Action

1 public IQueryable <Player> GetAllPlayers (ODataQueryOptions queryOptions) 2 3 {4 5 // top and skip 6 7 var filtered = db passed in by the client. players. skip (queryOptions. skip. value); 8 9 if (queryOptions. top. value> 0) 10 11 {12 13 filtered = filtered. take (queryOptions. top. value); 14 15} 16 17 return filtered. asQueryable (); 18 19}

 

 

Related 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.