在ASP.NET Web Forms中用System.Web.Optimization取代SquishIt


將一個ASP.NET Web Forms項目從.NET Framework 4.0升級至.NET Framework 4.5之后,發現SquishIt竟然引發了HTTP Error 500.0 - Internal Server Error

SquishIt是一個開源的支持ASP.NET的js/css打包工具,項目地址:https://github.com/jetheredge/SquishIt,出生早於Microsoft ASP.NET Web Optimization Framework(System.Web.Optimization)。

由於SquishIt不支持.NET Framework 4.5,只能棄之改用System.Web.Optimization。

以下是在實際的ASP.NET Web Forms項目中使用System.Web.Optimization的操作步驟:

1. 通過NuGet添加Microsoft ASP.NET Web Optimization Framework的引用

2. 在App_Code中添加BundleConfig.cs

using System.Web.Optimization;

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new StyleBundle("~/bundles/news.css")
            .Include("~/common/screen_base.css",
            "~/common/screen_news.css"));

        bundles.Add(new ScriptBundle("~/bundles/news.js")
            .Include("~/script/news_common.js", 
            "~/script/detail.js", 
            "~/script/share.js"));
    }
}

3. 在Global.asax的Application_Start中添加如下代碼:

BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);

4. 在.aspx中添加如下的js/css引用代碼:

<head>
    <title>IT新聞 - 博客園</title>
    <%: System.Web.Optimization.Styles.Render("~/bundles/news.css") %>
    <%: System.Web.Optimization.Scripts.Render("~/bundles/news.js") %>
</head>

5. 運行結果:

<link href="/bundles/news.css?v=sWIyZt7YgHul_fjj5uctLQ6NK499bBwg7ev8KRgojN01" rel="stylesheet"/>
<script src="/bundles/news.js?v=h7kkNXn83HAKCJJjw2VNEzbW_hHG-e5sAPoNOs_2Cx41"></script>

System.Web.Optimization與SquishIt的主要不同之處:

SquishIt會生成實際的文件保存在對應的路徑。

System.Web.Optimization只在內存中生成bundle文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM