Asp.net-Mvc

如何將 BundleConfig.cs 添加到我的項目中?

  • February 10, 2014

我有一個 ASP.Net MVC 項目,我想實現捆綁,但我在網際網路上可以找到的所有內容都指示我打開- 但是這個文件BundleConfig.csApp_Start我的項目中不存在。我在該文件夾中只有三個文件FilterConfigRouteConfigWebApiConfig.

創建解決方案時未生成捆綁配置(IIRC 一開始是一個空白的 ASP.NET MVC 項目)。

看起來這應該很容易做到,但我只是無法弄清楚。

PS 只是為了向那些沒有仔細閱讀的人澄清一下,這是針對從頭開始創建的 MVC4/.Net 4.5 應用程序。解決方案標記如下。

BundleConfig只不過是捆綁配置移動到單獨的文件。它曾經是應用程序啟動程式碼的一部分(過濾器、捆綁包、路由曾經被配置在一個類中)

要添加此文件,首先您需要將Microsoft.AspNet.Web.Optimizationnuget 包添加到您的 Web 項目中:

Install-Package Microsoft.AspNet.Web.Optimization

然後在 App_Start 文件夾下創建一個名為BundleConfig.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"));
       }
   }
}

RegisterBundles()然後修改您的 Global.asax 並添加對in的呼叫Application_Start()

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

引用自:https://stackoverflow.com/questions/21668280