Some time ago I had to use CherryPy in one of our companys projects. To quote the website, 'CherryPy is a pythonic, object-oriented HTTP framework.' - but the feature I found the most usefull was that you can expose methods so they can be called by typing in a url in any webbrowser.
I thought it would be nice to have something like that in C#, but had no time to create something like that.
Then a few days ago I found the MiniHttpd project here on codeproject - basically also an excellent and easy to use HTTP server framework. And then I thought why not use the MiniHttpd library to write a little something that would emulate the method exposure feature of CherryPy!
So thats what I did and what I want to present here.
Using the code
Usage is really simple!
At first reference my CherrySharp library. Then you just have to write a class that exposes methods using the
HttpVisible attribute like this:
public class ExampleClass
public int Add(int a, int b)
return a + b;
Then just call the
Init function of the
CherryServer giving it an instance of that class and the port on which the webserver should listen on:
CherryServer.Init(new ExampleClass(), 1234);
And thats it! Now "open" the exposed methods by typing in a url. Just use the method name as the 'filename' and append any parameters as a query string, like this:
Points of Interest
Whats happening behind the scenes? I use reflection to find all methods that have the
HttpVisible attribute and 'register' them as virtual 'files' in MiniHttpd.
Once a webrequest is made I look at the Query string to get the parameters and again use reflection to cast the parameters to their appropiate types and call the function of the instance of the class that was used in the
Methods that are made http visible can return stuff - it will just be converted to a string using the
ToString() method and be printed to the resulting web page (its actually only text, no html).
Init method has several overloads. You can specify wether error messages should be printed to the resulting html page describing the error when something went wrong (useful for debugging, but turned off by default).
You can also specify an object path name to be used for accessing the methods of the specific instance like this:
To make several different Instances and their http visible methods accessible through the same http server you can use the server id that gets returned by the Init method:
int serverId = CherryServer.Init(new ExampleClass1(), "a", 1234);
CherryServer.InitAdditional(new ExampleClass2(), "b", serverId);
HttpVisible attribute also has some properties to make method and parameter names case sensitive and to use a custom method name instead of the default one.