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!
That, sir, is a thing of beauty.
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”
Now with Preview 6 [ServiceContract] is not required. Things are getting more simple
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.
I’m surprised it still works like that. I swear it has changed 8 times already this year.