在 NancyFX 中将 / 重定向到 /index.html

Redirecting / to /index.html in NancyFX

我在自托管 Nancy 中提供静态内容并覆盖了根路径,并且还在我的自定义引导程序中添加了静态内容约定以重定向/到内容,如下所示:

conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", "Content"));

这在请求 URL 如 http://localhost/index.html but I would like http://localhost 重定向到 index.html 时工作正常。这似乎默认情况下不起作用。我做错了什么?

Nancy 将发现并自动挂接任何 IRequestStartup classes。像这样创建一个 class,一切都会好的 :)(超级骗子)

public class RootRedirector : IRequestStartup
{
    public void Initialize(IPipelines pipelines, NancyContext context)
    {
        if (context.Request.Url.Path == "/")
        {
           throw new RouteExecutionEarlyExitException(new RedirectResponse("/index.html"));
        }
    }
}

我最终用这样一个简单的模块解决了这个问题:

public class IndexModule : NancyModule
{
    public IndexModule()
    {
        Get["/"] = _ => Response.AsFile(Settings.Instance.GetFullContentPath("index.html"));
    }
}

Settings.Instance.GetFullContentPath 是我自己的方法,returns 指定文件在磁盘上的完整路径。