如何将Bootstrap添加到空的ASP.NET Core 2模板应用程序中?

4
在一个空的(模板)asp.net core 2应用中,添加Bootstrap包后,还需要什么才能访问Bootstrap?
我可以在依赖项下的NuGet节点下看到Bootstrap NuGet,但是没有任何Bootstrap文件在wwwroot中。
我已经添加了一个带有按钮的razor页面。然而,它显示为一个普通的按钮,Bootstrap没有被使用:
<button type="button" class="btn btn-primary">Primary</button>
2个回答

4

您需要使用Bower来安装文件(有关更多信息,请参见在ASP.NET Core中使用Bower管理客户端包)。

首先将bower.json.bowerrc文件添加到项目根目录中。

bower.json文件内容:

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.7",
    "jquery": "3.2.1"
  },
  "resolutions": {
    "jquery": "3.2.1"
  }
}

.bowerrc 的内容

{
  "directory": "wwwroot/lib"
}

然后在依赖项下的Bower文件夹中,您可以选择还原软件包,文件将被下载。

Bower restore

wwwroot

然后,在_Layout.cshtml文件中引用Bootstrap,开发时使用相对链接,发布时使用CDN链接。

<environment include="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
          asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

Startup.cs 中添加 UseStaticFiles 以使 Web 服务器能够返回 CSS 和 JS 文件。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) {
    ...
    app.UseStaticFiles();
    ...
}

当您右键单击解决方案以管理Bower包并添加Bootstrap时,输出会显示正在添加bower.json。但是我在解决方案中没有看到它。发生了什么? - 4thSpace
另外,当我添加 .bowerrc(文本文件)时,它会放在 bower.json 下面。这是正常的吗?我无法将它们断开连接。 - 4thSpace
我现在已经安装了文件,但是Bootstrap没有起作用。从这个引用<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">,浏览器在控制台中显示这个错误:css ignored due to mime type mismatch。如果我用CDN的引用替换它,它就可以工作了。有什么想法吗?在Chrome中,没有错误,但我得到了相同的视觉输出(没有Bootstrap)。 - 4thSpace
1
之前没有使用 app.UseStaticFiles() 中间件,现在一切都正常了。 - 4thSpace
我已经更新了答案,包括这一点。很高兴现在它能正常工作了。 - Brad Patton
新创建的MVC模板项目不会有任何bower文件,而是有一个bundleconfig文件。是否有一种方法可以在不使用bower的情况下向空项目添加这些前端支持? - Maverick Meerkat

0
文件不在js文件夹中。请尝试以下位置查找文件:
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>

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