How to serve static content in Nancy

Ian Oakes picture Ian Oakes · Nov 7, 2012 · Viewed 16.8k times · Source

I'm having trouble serving up static content such as JavaScript in Nancy.

For example using the self hosting sample I have added a test.js to the Views folder and added a

<script type="text/javascript" src="test.js"></script>

tag to the staticview.html page. If I view this page in the browser the JavaScript is executed correctly.

However when I run the sample the JavaScript is not executed. If I view the page in FireBug I see that I'm getting a 404 error for test.js.

I've tried adding

Get["{file}"] = p =>
{
    string path = string.Format("Views/{0}", p.file);
    return Response.AsJs(path);
};

and when I set a break point and execute Response.AsJs(path) in the immediate window I get a StatusCode of NotFound

I've also tried adding a StaticContentConvention such as

protected override void ConfigureConventions(NancyConventions conventions)
{
    base.ConfigureConventions(conventions);
    conventions.StaticContentsConventions.Add(
        StaticContentConventionBuilder.AddDirectory("/", "Views"));
    conventions.StaticContentsConventions.Add(
        StaticContentConventionBuilder.AddDirectory("Views", "Views"));
}

What am I doing wrong?

Answer

Christian Westman picture Christian Westman · Nov 22, 2012

You can configure static content using NancyConventions. Using the code from the following bootstrapper you can place all of your static contents (css/js/html/etc) inside a folder named "static" at the root of your application.

namespace Application
{
    public class ApplicationBootstrapper : DefaultNancyBootstrapper
    {
        protected override void ConfigureConventions(NancyConventions nancyConventions)
        {
            nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Static", @"Static"));
            base.ConfigureConventions(nancyConventions);
        }
    }
}

After this is done you can access static content such as scripts

<script type="text/javascript" src="/static/test.js"></script>

or css

<link rel="stylesheet" type="text/css" href="/static/styles.css">