The world’s simplest WCF Web API

Published on April 16, 2011

We all have to start somewhere, and I like to start with the simplest possible thing that works.  So I created a Console application and used NuGet to pull in the WebAPI.All package which contains all my dependencies.[1]

Once that was done, all I need is this:

using System;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.ApplicationServer.Http;

namespace SampleApi { class Program { static void Main(string[] args) { var host = new HttpServiceHost(typeof (ApiService), "http://localhost:9000"); host.Open(); Console.WriteLine("Browse to http://localhost:9000"); Console.Read(); } }

[ServiceContract]
<span class="kwrd">public</span> <span class="kwrd">class</span> ApiService {

    [WebGet(UriTemplate = <span class="str">&quot;&quot;</span>)]
    <span class="kwrd">public</span> HttpResponseMessage GetHome() {
        <span class="kwrd">return</span> <span class="kwrd">new</span> HttpResponseMessage() {
            Content = <span class="kwrd">new</span> StringContent(<span class="str">&quot;Welcome Home&quot;</span>, Encoding.UTF8, <span class="str">&quot;text/plain&quot;</span>)
        };

    }
}

}

 

If you point a browser to http://localhost:9000 you will get your first result.  Stay tuned for more exciting things to come.

 

[1]  Make sure you have the latest version of Nuget installed (ie. one from within the last week or so).  Also,  I swore at the project for a while until I realized that it was currently using the Client Profile version of the Framework.  This project needs the full version. Arrgh!