ASP.NET MVC ScriptBundle: change rendered output

百般思念 提交于 2021-02-08 10:19:26

问题


Is it possible to change the rendered output of a ScriptBundle in ASP.NET MVC? When configuring the bundles with EnableOptimizations = false, the output for each script included in the bundle is something like this:

 <script src="~/Scripts/path/to/script"></script>

I would like to change this "template" based on the ScriptBundle (for all bundles would also be fine). Is there a way to change this?


回答1:


Have a look at the below code, which will always give fresh file.

using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Optimization;

namespace TestProj
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/common").Include("~/Scripts/CommonScripts.js").WithLastModifiedToken());

            BundleTable.EnableOptimizations = false;
        }
    }

    internal static class BundleExtensions
    {
        public static Bundle WithLastModifiedToken(this Bundle sb)
        {
            sb.Transforms.Add(new LastModifiedBundleTransform());
            return sb;
        }
        public class LastModifiedBundleTransform : IBundleTransform
        {
            public void Process(BundleContext context, BundleResponse response)
            {
                foreach (var file in response.Files)
                {
                    var lastWrite = File.GetLastWriteTime(HostingEnvironment.MapPath(file.IncludedVirtualPath)).Ticks.ToString();
                    file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?v=", lastWrite);
                }
            }
        }
    }
}

The output will be

"/Scripts/CommonScripts.js?v=636180193140000000"

Here i am adding the last modified date of the file as query parameter. So whenever the file changes browser will get the fresh file all the time. Or instead of last updated time you can add version like '1.0.0' in the query parameter.




回答2:


I wrestled with MVC bundling for a long time too. It was great to begin with, but you start to fight a losing battle with it when you need to do anything out of the ordinary (like your question).

I'm sorry this doesn't directly answer your question, but I moved to WebPack because of issues like this, and have never looked back.

https://webpack.js.org



来源:https://stackoverflow.com/questions/48991907/asp-net-mvc-scriptbundle-change-rendered-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!