C# Web Server

Class Library
C#
GitHub Gist

What It Is

A very simple web server for testing things that require a website

Status

Last Reviewed:

It seems to work well, for what it is. I didn’t do a lot of testing, but this is really just a development utility.

Details

Sometimes I need a very quick website for testing something, and I was tired of cranking up a full ASP.NET project. I really just want to run something from LINQPad.

var server = new WebServer();
server.Start(8080, (c) => { c.Response.Write("Hello!"); });

// Nothing under the above line will run.
// It will just block there, waiting for a request

And that’s about it. It’s really just a thin wrapper around HttpListener.

To start the server, you pass it a port number, and a method that takes in an HttpListenerContext. There are some extension methods provided that make it easy to write text and bytes to the Response object.

It will block after server.Start() and just wait for a request. (Nothing under that will run, unless you push that into a separate thread.)

The only “feature” is that you can configure it to serve static files, which is handy when I have some CSS or JS to support what I’m doing. If you set the BaseDirectory property, it will try to find a file in that directory. If it does, it will write the bytes to the Response, set a MIME type, and never hit your provided method.

There’s a static dictionary called MimeTypes from which you can add different MIMEs you might want to provide (it’s pre-populated with about a dozen of the popular ones).

WebServer.MimeTypes.Add(".deane", "weird/file-format");

var server = new WebServer()
{
    BaseDirectory = @"C:\website"
};
server.Start(8080, respond);

void respond(HttpListenerContext content)
{
  // If there is a static file in C:\website
  // that matches the request, this will not run…
}