Building sample web api application in asp net mvc 4

Posted by Unknown
  
Building sample web APIapplication in asp net mvc 4

         In This post am going explain you building simple web API application in asp .net MVC 4,here i have given step by step explanation about web API implementation  

Open Visual Studio 2012 >> File >> New >> Project >> Select ASP.NET MVC4 Web Application Template >> Select Web API Template
1
2

















It will add automatically OData dependencies for us.Also you can install OData dependencies by using Nuget as well.
3
Create a new controller namedCustomersController by rightclicking the Controller folder.
9




Then add new class namedCustomer in the Model folder and add some properties like below

4
Also add one more folder named Domain and add a class namedCustomerDataContext, It contains a method Customers which return some customers information.
5

    For setting the OData first i need to do is set up my routing that can be get in to the Customers controller based on OData routing scheme not traditional web api routing schemes.Go to the WebApiConfig class in the App_Start folder and add a helper method GetImplicitEdm for defining entity data model.

6
                             This method will return IEdmModel which is a interface abstraction on the top of entity data models.ODataModelBuilder class will create set most of the entity data models automatically for you.The main thing you tell to the builder is entity sets are involved and then call the GetEdmModel method associated with the builder class,this will find all the properties on the object,find the types of those properties,look for navigation properties relates other objects in the model. Also add one more route (marked as yellow above) other than the web api route by calling the extension method MapODataRoute which accepts the parameters such as name of the route,a route prefix similar to the api route prefix in the default web api route and then call our helper method GetImplicitEdm.

                                  Then the next step is go to the customers controller and change our base classApiController to EntitySetController which is generic type takes two arguments,first one is the type of the entity controller represents and second one is the type of key property in that customer object and override Get method of type IQueryble and return our Customers.
8







Run the application and browse the url like below.It will return all the customers.
10







Then i am going to take individual customers. To do that there is a separate override base class called GetEntityByKey and querying by using linq.Note that this is a protected method it expose the service operation is actually a different public method on our base class and the public method will call this one.
11



Go and run the application and browse the url like below.
localhost:61592/odataCustomers("Niju")

I hope this will helps 


Labels:

Post a Comment

 
test