Introduction
This article will explain how to generate proxy objects of MVC and WebAPI controllers, using T4 templates and a wrapper for the controller class which exposes method metadata. This will allow you to make calls on object which will then map directly to a web service, mimicking that of WCF.
Background
I started this project when developing a solution to an assignment involving WebApi where I wanted to recreate a proxy object similar to the one WCF offers.
Using the code
The Wrapper and Attributes
To generate metadata the controller must inherit from its appropriate base class wrapper either ContractedController
or ContractedApiController
. These contracted controllers expose a method named GetContractInfo() which returns the metadata used by the T4 templates.
Methods that need exposing must be marked with the TransferContractAttribute
. This attribute by default defines all methods to use GET, this can be changed by defining the request type in the attribute constructor. For MVC method that return Json data the data type returned must also be specified.
A contracted MVC controller:
public class DemoController : ContractedController
{
[TransferContract(jsonReturnType: typeof(string))]
public JsonResult TestMethod()
{
return Json("SomeText", JsonRequestBehavior.AllowGet);
}
[TransferContract(requestType: RequestType.POST, jsonReturnType: typeof(string))]
[HttpPost]
public JsonResult TestMethod(string text)
{
return Json("Sent: " + text);
}
}
A contracted WebAPI controller:
public class DemoApiController : ContractedApiController
{
[TransferContract]
public string GetText()
{
return "SomeText";
}
[TransferContract(requestType: RequestType.POST)]
[HttpPost]
public string RepeatText(Message text)
{
return "Sent: " + text;
}
public class Message
{
public string Text { get; set; }
}
}
The Generator
Now that the controllers expose the GetContractInfo()
method the metadata can be accessed allowing you to generate a proxy object. I have written a C# and JavaScript T4 template which are bundled with the download.
Points of Interest
While creating this demo I had to alter the WebApi controller to take a message type due to the template generating sending data as JSON objects, which was not being picked up by the controller.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.