Nancyでの静的リソースアクセス

ナンシー静的リソースへのアクセスを行うには3つの方法があります。

デフォルト設定に従う。

Nancy supports multiple static content conventions at once and is shipped with a default convention that will look for files in the /content path of your application.

https://github.com/NancyFx/Nancy/wiki/Managing-static-content

これが一番簡単な方法です。
/content 以下にリソースファイルを配置するだけです。これはサブディレクトにも適用されます。


リソースディレクトリのカスタム設定(ヘルパー使用)

StaticContentConventionBuilder.AddDirectory()を使って、リソースディレクトリの割り付けを変更しています。

namespace NancyStaticResourceSample
{ 
    public class MyBootstrapper : DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            this.Conventions.StaticContentsConventions.Clear();  //contentフォルダの割り付け削除
            this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/aaa"));
        }
    }
}

リソースディレクトリのカスタム設定

ヘルパークラスが生成するラムダ相当を自前で作成しています。
(以下サンプルはかなりアレなので、参考程度にとどめてください^^;)

namespace NancyStaticResourceSample
{ 
    public class MyBootstrapper : DefaultNancyBootstrapper
    {
        protected override void ConfigureConventions(NancyConventions nancyConventions)
        {
            base.ConfigureConventions(nancyConventions);
            this.Conventions.StaticContentsConventions.Clear();  //contentフォルダの割り付け削除

            nancyConventions.StaticContentsConventions.Add((content, physicalRootPath) =>
            {
                var reqPath = content.Request.Path;

                if (reqPath.StartsWith("/aaa"))
                {
                    var res = new Response();
                    res.Contents = (st) =>
                    {
                        using (var src = new FileStream(System.IO.Path.Combine(physicalRootPath, @"aaa\image1.png"), FileMode.Open))
                        {
                            src.Seek(0, SeekOrigin.Begin);
                            for (var i = 0; i < src.Length; i++)
                                st.WriteByte((byte)src.ReadByte());
                        }
                    };
                    res.ContentType = "image/png";
                    return res;
                }

                return null;
            });
        }
    }
}

リソースディレクトリの無効化

静的リソースを扱わない場合は、リソースアクセス判定処理を無効化することで処理の高速化が見込めるでしょう。

namespace NancyStaticResourceSample
{ 
    public class MyBootstrapper : DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            container.Register<IStaticContentProvider, DisabledStaticContentProvider>();  //静的リソース判定結果を無条件でfalseとするProviderをRegistする
        }
    }
}