Friday 11 January 2013

Automatic creation of WebAPI proxy object

It has been a while since my last blog post but, I feel my current project is worth sharing. So, basically I have an assignment which means I get to play about with WebAPI, and after a while I started thinking maybe a proxy object could come in handy, the sort that WCF uses, so instead of having to know the location of each WebAPI method and how to serialise the data, I could call a method on an object and let it do the hard work;

So the concept behind my idea is: (I started this about 6 hours ago so it might still need tweaking)

An ApiController no longer inherits the ApiController class but a ContractedApiController class which is a sub-class of ApiController but contains the method GetWebApiInfo. This method returns a WebApiInfo object.

The WebApiInfo class contains two lists one containing WebApiMethodInfo objects, the other containing WebApiClassDefinition objects. The class names a pretty much explain the classes, the WebApiMethodInfo class contains a method name, request type (get, post, ect.), return type, and a dictionary storing parameter names and types. The WebApiClassDefinition stores a class name along with a dictionary of property names and types.

When the GetWebApiInfo is called, it first searches for all methods that hold the custom attribute WebApiContractAttribute, then maps these methods onto WebApiMethodInfo objects, if any non-system objects (need to work on this) are found as parameters or return types they are mapped onto WebApiClassDefinition objects. Finally when all this is done the WebApiInfo object is returned as Json or XML.

To utilise this I created a T4 template that calls GetWebApiInfo and based on the metadata received, generates a WebAPI proxy object and data transfer objects locally. As you can see below intellisense is picking up the "Get" and "WebApiMethod", and the "TestClass" class has been generated.


I'll be back with any more developments I have.

Liam

3 comments:

  1. Hello, Liam. This project seems interesting. What are your developments on it? Do you host it somewhere like GitHub?

    ReplyDelete
    Replies
    1. Hi, I was in the process of providing a demo on CodeProject and got side tracked halfway through, but your comment reminded me to finish it so just waiting for it to be approved :D

      Liam

      Delete
    2. http://www.codeproject.com/Tips/535260/Proxy-Object-Generation-for-MVC-and-WebAPI-Control

      Delete