Self Hosted WebServer using OWIN
I've been playing about with OWIN and Katana recently and was pleasantly surprised with how easy it was to get up and running serving static files from a console application.
- Create a new console project.
- Install two packages:
- install-package Microsoft.Owin.StaticFiles
- install-package Microsoft.Owin.SelfHost
- Create a startup object.
- Start a WebApp with a root url.
- Run the application.
- Profit!
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Owin;
using System;
#if DEBUG
[assembly: OwinStartup(typeof(OwinTestApp.DebugStartup))]
#else
[assembly: OwinStartup(typeof(OwinTestApp.ProductionStartup))]
#endif
namespace OwinTestApp
{
class Program
{
static void Main(string[] args)
{
string url = (args.Length > 0) ? args[0] : "http://localhost:12345";
using (WebApp.Start(url))
{
Console.WriteLine("Server listening at : " + url + ". Press a key to stop.");
Console.ReadKey();
}
}
}
public class DebugStartup
{
public void Configuration(IAppBuilder app)
{
app.UseErrorPage();
app.UseWelcomePage("/");
}
}
public class ProductionStartup
{
public void Configuration(IAppBuilder app)
{
var options = new FileServerOptions
{
EnableDirectoryBrowsing = true,
FileSystem = new PhysicalFileSystem(".")
};
app.UseFileServer(options);
}
}
}
The example above shows a method of using different OwinStartup attributes to identify which startup object to use.
The DebugStartup class uses the default smiley welcome page:
and the ProductionStartup class uses a simple file system configuration to serve static files from the root folder. Turning on EnableDirectoryBrowsing shows the binaries in the build folder.
For home projects, the Nancy web framework was my favourite for building .Net web applications (hosted on IIS or self-hosted) but now I'm torn between using the self-hosting or Helios-hosted version of OWIN. More experiments are needed.