OData Protocol (Open Data Protocol) was released by Microsoft in 2007. The current version has been upgraded to 4.0. Now OASIS (Organization for the Advancement of Structured Information Standards) has approved this protocol standard. OData is based on REST principle to offer HTTP CRUD service. This protocol also provides special query language expression to help clients filter the query result and customize the data model. This enables the users don’t have to largely change their code to get the data structure and format they want. Now both ASP.NET CORE and ASP.NET FRAMEWORK support OData. This article will reveal how to make OData work on these two frameworks and shows the real examples of using OData.
OData Expression Language
OData Query Language
Odata Query Options | Meaning |
$top = n | Return the first nth data |
$skip = n | Skip the first nth data |
$Orderby | Return the data in ascending or descending or |
$filter | Return the data which satisfies the filter condition |
ASP.NET FRAMEWORK
Download OData package
Now, we have to append WebApiConfig.cs
Controller must inherit ODataController class
Then for Web Api, add [EnableQuery] Attribute for the HTTP method
ASP.NET CORE
Same to ASP.NET FRAMEWORK, we have to download OData package firstly
Then add codes shown below
Lastly, remember to add [EnableQuery] Attribute prior to the HTTP method
OData Example
The following example will use Product class below
Then set the data for testing
After the execution of Visual Studio or any other IDE, enter the URL
You then will see the result json like this.
On the other hand, if you want to see both fields (Name and Price), you need to fix the URL
The result will look like
Say you then have a new request, you want to see the price of the product list in the order from low to high, you just need to add $OrderBy semantics to the URL
Conclusion
The above example manifests the potential of OData. We just have to append query language to get the data structure we want. However for the other Restful API method, we may have to add and fix large segments of the original code written to achieve our goal. For the OData, we only need to add or change small part of code to allow OData work on either ASP.NET FRAMEWORK or ASP.NET CORE framework. Hence, OData is an useful and flexible standard to achieve Restful architecture.