Skip to content
David Cumps
Nancy + Static Content + OWIN + SystemWeb

Nancy + Static Content + OWIN + SystemWeb

Originally published on my old blog at cumps.be on January 6, 2014.

I’ve just started building a new site with Nancy. It will run on IIS, and I chose to host it through OWIN instead of Nancy’s own ASP.NET host. Everything worked until I got to managing static content: the files simply weren’t served.

The 404

My site requests its CSS and JavaScript files from /css and /js. According to the wiki, this should be simple enough: put the files under /Content/Styles and /Content/Scripts and map them. In my Bootstrapper, I have the following:

protected override void ConfigureConventions(NancyConventions conventions)
{
    base.ConfigureConventions(conventions);

    conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/css", @"/Content/Styles"));
    conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/js", @"/Content/Scripts"));
}

Reload, and nothing: every request under /js came back as a 404 instead of the file.

Two settings that fix it

As it turns out, when you use Microsoft.Owin.Host.SystemWeb, you need some additional configuration to get static content working.

Inside your OWIN Startup.cs, you need a stage marker:

using Microsoft.Owin.Extensions;
using Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseNancy();
        app.UseStageMarker(PipelineStage.MapHandler);
    }
}

UseStageMarker(PipelineStage.MapHandler) makes the OWIN pipeline, and with it Nancy, run before IIS picks a handler for the request, so Nancy gets the request instead of IIS’s own static file handler.

And inside your Web.config you need to have:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

runAllManagedModulesForAllRequests sends requests for files like .js and .css through the managed modules, OWIN included. Without it, IIS treats them as plain static files and Nancy never sees them.

With those two changes, static content is being served correctly.

You May Also Like