Introduction
OData (Open Data Protocol) is an open protocol for sharing the data. It is OASIS (Organization for the Advancement of Structured Information Standards) standard which defines best practice for building and consuming REST API.
In this article we learn how to create OData services using ASP.NET Web API. Here, I am not using entity framework as data access. I am just using in-memory data as a data source.
The following steps are required to perform to use OData with Web API.
Step 1: Create Web API solution and install OData for Asp.NET,
First step is to create empty solution for Web API and installed ASP.NET OData using the following command,
Step 2: Create model class
Create model class which is used in communication.
- public class TestData
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Role { get; set; }
- }
Step 3: Create In-memory data source
When we use OData service with Web API, Entity Framework is best suited. This is quite complex in demo project. So here I am using in-memory data source and it is very simple and straightforward. In data source, I have created some data and return the list.
- public List<TestData> CreateTestData()
- {
- List<TestData> data = new List<TestData>();
- data.Add(new TestData { Id = 1, Name = "Jignesh", Role = "Project Manager" });
- data.Add(new TestData { Id = 2, Name = "Tejas", Role = "Architect" });
- data.Add(new TestData { Id = 3, Name = "Rakesh", Role = "Lead" });
-
- return data;
- }
Step 4: Define Controller
Next step is to define controller. Controller class is needed to inherit from ODataController and base class of ODataController is ApiController. ODataController class has methods for reading and writing data using OData format.
EnableQuery Attribute class enables querying using OData query syntax. This attribute is responsible to validate all incoming queries so that we can avoid processing malicious queries.
The body of controller, I have defined Get method that returns value from in-memory data source.
- public class TestDataController : ODataController
- {
- [EnableQuery]
- public IHttpActionResult Get()
- {
- var result = CreateTestData().AsQueryable();
- return Ok(result);
- }
- }
Step 5: Configure the Endpoint
The final step is to define the end point. Endpoint configured in WebApiConfig.cs file under App_Start. Configuration code contains two things,
- Create EDM (Entity Data Model)
- Adding Route
The Entity Data Model is used to create service Meta. The ODataConventionModelBuilder is used to create an EDM. if we required more control on EDM than we can use ODataModelBuilder class to create the EDM. MapODataServiceRoute extension is used to define OData v4 route. Point to remember, application has multiple OData endpoints then create separate route for each.
- namespace WebAPITest
- {
- using Microsoft.OData.Edm;
- using System.Web.Http;
- using System.Web.OData.Batch;
- using System.Web.OData.Builder;
- using System.Web.OData.Extensions;
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
- config.EnsureInitialized();
-
- }
- private static IEdmModel GetEdmModel()
- {
- ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
- builder.Namespace = "WebAPITest";
- builder.ContainerName = "DefaultContainer";
- builder.EntitySet<TestData>("TestData");
- var edmModel = builder.GetEdmModel();
- return edmModel;
- }
- }
- }
Service Testing
In preceding example, I have defined the GET method in controller. To test OData service, we can use fiddler. Here I have shared some test URL and result as following.
Get Service document
URL: http://localhost:24367/ Result:
- {
- "@odata.context":"http://localhost:24367/$metadata","value":[
- {
- "name":"TestData","kind":"EntitySet","url":"TestData"
- }
- ]
- }
Get Service metadata
URL: http://localhost:24367/$metadata Result:
Queries on data source
Get All Test data:
URL: http://localhost:24367/TestData Result:
- {
- "@odata.context":"http://localhost:24367/$metadata#TestData","value":[
- { "Id":1,"Name":"Jignesh","Role":"Project Manager" },
- { "Id":2,"Name":"Tejas","Role":"Architect" },
- { "Id":3,"Name":"Rakesh","Role":"Lead" }
- ]
- }
Select only Name filed from source:
URL: http://localhost:24367/TestData?$Select=Name Result:
- {
- "@odata.context":"http://localhost:24367/$metadata#TestData(Name)","value":[
- { "Name":"Jignesh"},{"Name":"Tejas"},{"Name":"Rakesh"}
- ]
- }
Filter by Role:
URL: http://localhost:24367/TestData?$filter=contains(Role,'Ar')
Result:
- {
- "@odata.context":"http://localhost:24367/$metadata#TestData","value":[
- { "Id":2,"Name":"Tejas","Role":"Architect" }
- ]
- }
Filter by Name:
URL: http://localhost:24367/TestData?$filter=Name eq 'Jignesh'
Result:
- {
- "@odata.context":"http://localhost:24367/$metadata#TestData","value":[
- { "Id":1,"Name":"Jignesh","Role":"Project Manager" }
- ]
- }
Summary
OData has now become standard way to share the data between two application software. In this article we learnt, how to use create OData endpoint in Web API. Hope this will help you.
Read more articles on ASP.NET: