The world’s simplest WCF Web API

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]
    public class ApiService {

        [WebGet(UriTemplate = "")]
        public HttpResponseMessage GetHome() {
            return new HttpResponseMessage() {
                Content = new StringContent("Welcome Home", Encoding.UTF8, "text/plain")
            };

        }
    }

}

 

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!

5 thoughts on “The world’s simplest WCF Web API

  1. I so hate that client profile thing. Last week someone on my team lost hours trying to build a sample due to this. I had hit it before so when he asked me I was like “wait you said this is a console app right? Bet it’s the client profile” 

  2. Thanks, Darrel! This is actually really helpful because I wasn’t 100% sure how to put together a WebAPI setup outside of it being couched inside of MVC. Awesome.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>