如何在南希投放静态内容 [英] How to serve static content in Nancy

查看:90
本文介绍了如何在南希投放静态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Nancy中提供静态内容(例如JavaScript)时遇到了麻烦.

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

例如,使用自托管示例,我添加了一个将test.js添加到Views文件夹并添加

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>

标记到staticview.html页面.如果我在浏览器中查看此页面,则JavaScript正确执行.

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

但是,当我运行示例时,未执行JavaScript.如果我在FireBug中查看该页面,则会看到test.js出现404错误.

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.

我尝试添加

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

当我设置一个断点并在立即窗口中执行Response.AsJs(path)时,我得到一个NotFound的StatusCode

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

我还尝试过添加StaticContentConvention,例如

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"));
}

我在做什么错了?

推荐答案

您可以使用NancyConventions配置静态内容.使用以下引导程序中的代码,您可以将所有静态内容(css/js/html/etc)放在应用程序根目录下名为"static" 的文件夹中.

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>

或css

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

这篇关于如何在南希投放静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆