在ASP.Net 5 MVC 6中添加.css文件

3

我正在尝试探索MVC6应用程序。我选择了Framework 4.6和Empty ASP.Net预览模板。使用Visual Studio 2015。

我在wwwroot/css目录下有一个.css文件。

现在我想在index.cshtml中使用它,如下:

<link href="../../css/css.css" rel="stylesheet" />

也尝试过

<link href="~/css/css.css" rel="stylesheet" />

但是它没有工作。这里需要任何技巧吗?

在我的MVC 6应用程序中,<link href="~/css/css.css" rel="stylesheet" />工作正常。但是我将其放在_Layout.cshtml文件中,我认为它应该可以工作。 - alek kowalczyk
是的,它应该可以工作。如果您使用默认的起始Web模板,则此引用也将在_layout.cshtml中使用。 - Thom Kiesewetter
4个回答

7

您需要告诉ASPNET5使用静态文件。在startup.cs中添加:

app.UseStaticFiles();

在Configure()函数中。


1
你需要在布局页面上添加文件,在MVC 6中,您可以指定要在开发、暂存或生产环境中使用哪个文件,具体取决于您的工作位置。 示例:
<environment names="Development">
  <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
  <link rel="stylesheet" href="~/css/site.css" />
  <link rel="stylesheet" href="~/css/YourStyleFile.css" />
</environment>
<environment names="Staging,Production">
  <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

1
尝试这个。
  @section scripts{
       <link href="~/css/css.css" rel="stylesheet" asp-file-version="true" />
    }

但建议将文件添加到布局中。

欢迎来到Stack Overflow!我想向您推荐http://stackoverflow.com/help/how-to-answer,以便回答问题。需要注意的是,您的答案可能会长期存在,并且有许多不同的人查看您的答案,因此请尽量提供答案的理由。 - Peter Hornsby

-2

前往您的 App_Start 文件夹 > BundleConfig.Cs > 然后找到类似于以下代码块的代码块

 bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                           "~/Content/themes/base/jquery.ui.core.css",
                           "~/Content/themes/base/jquery.ui.resizable.css",
                           "~/Content/themes/base/jquery.ui.selectable.css",
                           "~/Content/themes/base/jquery.ui.accordion.css",
                           "~/Content/themes/base/jquery.ui.autocomplete.css",
                           "~/Content/themes/base/jquery.ui.button.css",
                           "~/Content/themes/base/jquery.ui.dialog.css",
                           "~/Content/themes/base/jquery.ui.slider.css",
                           "~/Content/themes/base/jquery.ui.tabs.css",
                           "~/Content/themes/base/jquery.ui.datepicker.css",
                           "~/Content/themes/base/jquery.ui.progressbar.css",
                           "~/Content/themes/base/jquery.ui.theme.css"));

然后在这里添加你的CSS文件路径

编辑1

现在你已经告诉我你正在使用一个空的预览模板,你有两个选择,

  1. 添加App_start文件夹并添加上述代码块,然后在您的Layout.cshtml文件中添加以下行:

    @Styles.Render("~/Content/themes/base/css")
    

或者

  1. 在您的Layout.cshtml文件中,引用方式与通常相同,但您需要在共享视图中使用它,以便其在整个站点中传递

没有 App_Start 文件夹。 - s.k.paul
@SimonPrice OP正在使用Asp.Net 5,而你正在使用之前的版本。项目布局已经发生了重大变化。不再有App_Start文件夹。 - Domysee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接