我有一个 ASP.Net MVC 项目,我想实现捆绑,但我在互联网上找到的所有内容都指示我在 App_Start
中打开 BundleConfig.cs
-但是这个文件在我的项目中不存在。我在该文件夹中只有三个文件:FilterConfig
、RouteConfig
和 WebApiConfig
。
当我创建解决方案时未生成捆绑配置(IIRC,它在开始时是一个空白的 ASP.NET MVC 项目)。
看起来这应该很容易做到,但我就是想不通。
附言只是为了向那些没有仔细阅读的人澄清,这是针对从头开始创建的 MVC4/.Net 4.5 应用程序的。解决方案如下所示。
最佳答案
BundleConfig
只不过是移动到单独文件的捆绑配置。它曾经是应用程序启动代码的一部分(过滤器、 bundle 、路由曾经在一个类中配置)
要添加此文件,首先需要将 Microsoft.AspNet.Web.Optimization
nuget 包添加到您的 Web 项目中:
Install-Package Microsoft.AspNet.Web.Optimization
然后在 App_Start 文件夹下创建一个名为 BundleConfig.cs
的新 cs 文件。这是我的(ASP.NET MVC 5,但它应该适用于 MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
然后修改您的 Global.asax 并在 Application_Start()
中添加对 RegisterBundles()
的调用:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
一个密切相关的问题:How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
关于asp.net-mvc - 如何将 BundleConfig.cs 添加到我的项目中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138678/