Archive

Archive for April, 2013

A minimal, WCF based, rest service in C#

April 13, 2013 4 comments

There are many ways to implement a REST service. WCF provides one and it is pretty straight forward.

Start by adding a new C# console application;

image

Add references to System.ServiceModel and System.ServiceModel.Web

image

Add a service contract decorate methods with additional rest verb information [WebGet] or [WebInvoke(Method="…")].

image

Add an implementation

image

Add a service host. I setup all configuration using code instead adding configuration to app.config – just to keep things to a minimum.

image

If you are not running as an administrator you must allow the current user to start a service on this address. In this case, start a command prompt as an administrator and execute;

> netsh http add urlacl url=http://+:8899/MyService user=<username>

(ref: http://stackoverflow.com/questions/885744/wcf-servicehost-access-rights)

All done. Start the service. Get methods can simply be tested in a browser:

image

Using powershell v3 we can test all methods:

Invoke-RestMethod http://localhost:8899/MyService/SayWhat?Message=Yay -Method Put

$x = Invoke-RestMethod http://localhost:8899/MyService/SaySomething?i=111
$x.string.‘#text’

Resulting in “Yay111” being displayed.

Categories: Uncategorized