ASP.NET MVC ScriptBundle:更改呈现的输出 [英] ASP.NET MVC ScriptBundle: change rendered output

查看:82
本文介绍了ASP.NET MVC ScriptBundle:更改呈现的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在ASP.NET MVC中更改ScriptBundle的呈现输出?当使用 EnableOptimizations = false 配置分发包时,分发包中包含的每个脚本的输出如下所示:

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>

我想基于ScriptBundle更改此模板"(对于所有包来说也可以).有办法改变吗?

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?

推荐答案

看看下面的代码,它将始终提供新鲜的文件.

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);
                }
            }
        }
    }
}

输出将是

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

在这里,我要添加文件的最后修改日期作为查询参数.因此,每当文件更改时,浏览器将始终获取新文件.或者,您可以在查询参数中添加"1.0.0"之类的版本,而不是上次更新时间.

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.

这篇关于ASP.NET MVC ScriptBundle:更改呈现的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆