Home > Uncategorized > A minimal, WCF based, rest service in C#

A minimal, WCF based, rest service in C#

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.

Advertisements
Categories: Uncategorized
  1. July 3, 2013 at 1:13 pm

    imo self-hosting a webapi project is more clean, also I always associate restful services with transport over http, would you ever use a different binding than webhttpbinding? If no, I really don’t see the point if making it a wcf-service. Just some thoughts 😉

  2. July 4, 2013 at 10:47 pm

    Using WCF is pretty clean imo and for someone knowing WCF but not wepapi it might be useful. I like that the general WCF framework is able to handle restful services along with all its other capabilities. Having that said I think webapi is a very good option indeed and most likely it will be a better solution since it is more “specialized” framework.

  3. August 10, 2013 at 8:49 pm

    A very good tutorial on self hosted wep api projects can be found here; http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api.

  4. John
    February 6, 2017 at 10:58 pm

    Thanks for this post, work great. Was looking for a lightweight API that could be leveraged for retrieving information about object progress and this fits the bill!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: