Wednesday, August 20, 2014

Step by step OData REST Service with MVC Web API


In this article we'll create an OData RESTful Service using the WebAPI  inside an Asp.Net MVC application , with support for GET operations. A wider  tutorial about how to create a Web API OData v4.0 Service with support for all the CRUD operations (Create - Retrieve - Update - Delete), can be seen here 

For this tutorial, we'll  create a Web API and enable it as a RESTful OData application, to handle HTTP  GET requests.   
We'll create our RESTful OData Web API from scratch in 3 simple steps:
1) create an MVC app & install/update Web API and OData assemblies
2) create the data Model;
3) create an ApiController and set the "Queryable" attribute over the Action Methods

The REST architecture enables handling HTTP requests according to several verbs: GET is for reading data, POST is for creating a new record, PUT is for updating ALL the fields of some record, PATCH (or PUT again) is for updating partially some record, and DELETE is for erasing a record.

At this example we'll use an XML file where the data is stored, and we'll expose it using the OData protocol, supporting of course sorting ($orderby)  and paging ($skip & $top) :


1) Step #1 : create an MVC app & install/update Web API and OData .dlls:

First, create a new EMPTY Asp.Net MVC Application:




Then, UPDATE the Web API references, by opening the NuGet Console and typing :
Update-Package Microsoft.AspNet.WebApi -Pre




Next, install the OData package by typing:
Install-Package Microsoft.AspNet.WebApi.OData -Version 5.0.0




2) Step #2 : create the data Model : 



 public class Note
    {
        public int ID { get; set; }
        public string To { get; set; }
        public string From { get; set; }
        public string Heading { get; set; }
        public string Body { get; set; }
        public Note()
        {

        }
        public Note(int ID, string To, string From, string Heading, string Body)
        {
            this.ID = ID;
            this.To = To;
            this.From = From;
            this.Heading = Heading;
            this.Body = Body;
        }
    }

Important: you MUST declare a parameterless constructor in your model, because the serializer will need it to render the data at the Controller.

3) Step #3 : create an ApiController and set the "Queryable" attribute over the Action Methods : 




Why do we mark the Action Method as "Queryable"? That's the key to enable the OData HTTP Service: Take a look at the attribute's description:


Important:   The Action method's name MUST be set according to the HTTP verbs : Get for HTTP GET, Post for HTTP POST, and so on.

Now we get the data from the XML file, and return an IQueryable<> collection :
public class NotesController : ApiController
    {
        [Queryable]
        public IQueryable<Note> Get()
        {
            List<Note> data = new List<Note>();
            XDocument xdoc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/data.xml"));
            foreach (var note in xdoc.Descendants("note"))
            {
                data.Add(new Note(
                    Convert.ToInt32(note.Descendants("id").FirstOrDefault().Value),
                    note.Descendants("to").FirstOrDefault().Value,
                    note.Descendants("from").FirstOrDefault().Value,
                    note.Descendants("heading").FirstOrDefault().Value,
                    note.Descendants("body").FirstOrDefault().Value
                    ));
            }
            return data.AsQueryable<Note>();
        }
    }

At the code above, i remarked the most important points with red .

Finally, we set the route template at the WebApiConfig file :

That's all. Build & run the service :
Make a HTTP GET request using the OData protocol :




As you see, we have paging ($skip & $top) and sorting ($orderby) support : 



That's all
In this post we've seen how to setup an OData RESTful HTTP Service using the Web API  inside an Asp.Net MVC application , with support for GET operations. 

Happy programming.....
    By Carmel Shvartzman
כתב: כרמל שוורצמן