Introduction
In our previous article, we have discussed Odata, It's advantages, and how to expose Odata endpoints in the Web API. You can read them here.
Expose Odata Endpoints Without Entity Framework and Performing CRUD
In this article, we will learn how to consume OData from a JavaScript client. I am planning to implement Odata in a Web API from scratch and we will consume Odata endpoints from the JavaScript client, it will help you to understand the fundamental concepts of Odata if you are very new in this field.
I will assume that you have a fundamental understanding of Odata and its uses and advantages. If not then the following quick introduction is for you.
OData stands for Open Data protocol that is proposed and introduced by Microsoft. Then it was adopted by the industry as an open and uniform platform to expose data to the outer world. So, it provides the idea of sharing and consuming data irrespective of platform and protocol.
You can get more information about Odata here.
As said, in this example we will implement Odata endpoints from scratch and for that we will use SqlServer and the Entity Framework.
First things first, create one Web API 2.0 application in the solution, in this example, I am using Visual Studio 2012. If you are using Visual Studio 2010 or lower then you need to have the MVC 4 template to get the Web API and need to update Web API application to Web API 2.0. Then install the Odata package from the NuGet Package Manager. Here is the package for reference.
Web API 2.2 Odata is the core package and in this of package installation it will ask you to allow installation of its a dependent package. So please accept the prompt option and allow it to install its dependent packages.
Now, the application is Odata compatible and we are allowed to expose Odata endpoints from applications.
Here is our sample table that we will use to expose Odata endpoints.
Now, add an Entity Framework to generate a model from the database. Here is the model in my sample application. To add Entity Framework, please refer to any good tutorial if you are very new to Entity Framework.
Fine, we will now add a controller and a few lines of code within the controller. Here is a sample controller to expose OData.
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Web.Http.ModelBinding;
- using System.Web.Http.OData;
- using System.Web.Http.OData.Routing;
- using OdataAPI;
- using OdataAPI.Models;
-
- namespace OdataAPI.Controllers
- {
- public class userController : ODataController
- {
- private ApiSecurityEntities db = new ApiSecurityEntities();
-
- [Queryable]
- public IQueryable<UserMaser> GetUser()
- {
- return db.UserMaser;
- }
-
- [Queryable]
- public IQueryable<UserMaser> GetUserById([FromODataUri] int key)
- {
- return db.UserMaser.Where(um => um.id == key);
- }
-
- }
- }
Now, let's discuss the controller a little bit. First of all the controller is inherited from the ODataControler class, not like from a Controler of an ApiController class. So, OdataController is the base class of a “user” controller. Then we implemented two methods/actions and both actions are decorated by the Queryable attribute; it will ensure that both actions will available as Odata endpoints.
The first action will return data as a query of the Odata standard and the second function is ready to return a single Entity of the UserMaster class by taking Id as an argument.
Ok, we have finished our controller implementation, now the next task is to register the Odata controller in the route so that when someone will try to point the Odata controller, the request will hot in the appropriate controller.
To register the Odata route just open the WebApiConfig.cs file of the application and modify it accordingly.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using System.Web.Http.OData.Builder;
- using Microsoft.Data.Edm;
- using OdataAPI.Models;
-
- namespace OdataAPI
- {
- public static class WebApiConfig
- {
- private static IEdmModel GenerateEdmModel()
- {
- var builder = new ODataConventionModelBuilder();
- builder.EntitySet<UserMaser>("user");
- return builder.GetEdmModel();
- }
- public static void Register(HttpConfiguration config)
- {
-
- config.MapHttpAttributeRoutes();
-
- config.EnableQuerySupport();
- config.Routes.MapODataRoute("odata", "odata", GenerateEdmModel());
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
Now, the Odata endpoint is registered to the routing engine and all the configurations have been done in the server and now we can host out application and test the application using Fiddler as the client to ensure that everything is working correctly and from the JavaScript client we can access it.
If we hit the following URL then we should get all the data from the UserMaster table that we are getting in Fiddler.
http://localhost:10020/odata/user
Ok, everything is fine, now let's create one ajax() function of jQuery to call the Odata endpoint. Have a look at the following example.
- <script>
- $(document).ready(function () {
- $.ajax({
- type: "GET",
- url: "http://localhost:10020/odata/user?$top=1",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- alert(JSON.stringify(response));
- },
- failure: function (response) {
- alert(response.d);
- }
- });
- });
-
- </script>
This piece of code will work as an Odata client and consume data from Odata endpoints. In the success callback function, we are printing a value.
We are firing an Odata query to the Odata endpoint as in the following.
http://localhost:10020/odata/user?$top=1
We are getting only one record, it's the top 1 record from the table. If you are interested then you are allowed to fire any odata parameter in this endpoint.
Conclusion
We have now learned how to implement an Odata endpoint and consume it from a JavaScript client. I hope this article will help you to understand the concept of Odata in the Web API.