Simple .NET standalone web server

The other day I got frustrated that I couldn’t find a code example of a simple .NET OWIN standalone (i.e. not using IIS) web server (i.e. not a REST server) for .NET. After some research and trial-and-horror I came up with the following:

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.SelfHost;

namespace WebServer
{
    class Program
    {
        static void Main(string[] args)
        {
            const string serviceBaseUri = "http://localhost:4578/";
            var config = new HttpSelfHostConfiguration(serviceBaseUri);
            using (var server = new HttpSelfHostServer(config, new MyMessageHandler()))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Ctrl+C to quit.");
                Console.ReadLine();
            }
        }
    }

    public class MyMessageHandler : HttpMessageHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Debug.Print(request.ToString());
            var res = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Hello, World!") }; 
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(res);   // Also sets the task state to "RanToCompletion"
            return tsc.Task;
        }
    }
}

Enjoy!

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: