首页 > 编程语言 >ASP.NET MVC5 Bundling and Minification

ASP.NET MVC5 Bundling and Minification

时间:2023-11-24 15:22:06浏览次数:30  
标签:MVC5 string url Minification Content var new NET css

代码

var myScriptBundle = new ScriptBundle("~/bundles/script").Include("~/Scripts/myscript.js");
bundles.Add(myScriptBundle);

var myStyleBundle = new StyleBundle("~/Content/css").Include("~/Content/Login/mycss.css")
bundles.Add(mfaStyleBundle);

不起作用?

有两种办法使其生效
第一就是修改web.config

 <system.web>
        <compilation  debug="false" />
 </system.web>

第二就是在代码中直接指定,不管web.config中是不是debug都使其生效

 BundleTable.EnableOptimizations = true;

缓存问题

如果修改了css和js文件,而用户浏览器存在缓存,不能无感更新,用户要手动强制刷新或者清除缓存
解决该问题,我们希望每次文件发布后,都有不同的“版本号”,如果未更改文件,那么也不用更新“版本号”
你也看出来了,这个“版本号”与文件内容有关系,所以取文件哈希值最合适

public class BundleTransformer : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        foreach (var file in response.Files)
        {
            using (var fileStream = File.OpenRead(HostingEnvironment.MapPath(file.IncludedVirtualPath)))
            {
                var hashBytes = new MD5CryptoServiceProvider().ComputeHash(fileStream);
                var version = string.Join(null, hashBytes.Select(value => value.ToString("x2")));
                file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, $"?v={version}");
            }
        }
    }
}

使用

var myScriptBundle = new ScriptBundle("~/bundles/script").Include("~/Scripts/myscript.js");
myScriptBundle .Transforms.Add(new BundleTransformer());//new
bundles.Add(myScriptBundle);

var myStyleBundle = new StyleBundle("~/Content/css").Include("~/Content/Login/mycss.css")
myStyleBundle.Transforms.Add(new BundleTransformer());//new
bundles.Add(mfaStyleBundle);

CSS 中图片路径失效问题

一般我们写css的时候,比如背景图都会写下相对路径

div{background-img: url(../images/logo.png);}

当我们的虚拟路径(假设设置为/Content/css)和css文件(/Content/css/order/index.css)的路径不一致的时候,css文件中的图片这个时候就会出现找不到的问题
所以,此时css中的image的路径应该相对虚拟路径,而不是相对css文件了
就没有好办法吗?有

var myStyleBundle = new StyleBundle("~/Content/css")
.Include("~/Content/XXX/index.css", new CssRewriteUrlTransform())
.Include("~/Content/YYY/index.css", new CssRewriteUrlTransform());//new

bundles.Add(myStyleBundle);

我们看下CssRewriteUrlTransform的实现

public class CssRewriteUrlTransform : IItemTransform
{
    public CssRewriteUrlTransform()
    {
    }

    internal static string RebaseUrlToAbsolute(string baseUrl, string url)
    {
        if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(baseUrl) || url.StartsWith("/", StringComparison.OrdinalIgnoreCase))
        {
            return url;
        }

        if (!baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase))
        {
            baseUrl += "/";
        }

        return VirtualPathUtility.ToAbsolute(baseUrl + url);
    }

    internal static string ConvertUrlsToAbsolute(string baseUrl, string content)
    {
        if (string.IsNullOrWhiteSpace(content))
        {
            return content;
        }

        Regex regex = new Regex("url\\(['\"]?(?<url>[^)]+?)['\"]?\\)");
        return regex.Replace(content, (Match match) => "url(" + RebaseUrlToAbsolute(baseUrl, match.Groups["url"].Value) + ")");
    }

    public string Process(string includedVirtualPath, string input)
    {
        if (includedVirtualPath == null)
        {
            throw new ArgumentNullException("includedVirtualPath");
        }

        string directory = VirtualPathUtility.GetDirectory(includedVirtualPath.Substring(1));
        return ConvertUrlsToAbsolute(directory, input);
    }
}

代码一看就懂,通过正则表达式给你重写下css中的url路径

但是,偏偏又有一种场景,你的网站如果部署IIS 的 application,那么你会发现上面的写法又又失效了
比如你的网站访问url是:http://localhost/sample/
你期望css中image url是: http://localhost/sample/content/images/logo.png
但是上面的方法得到的却是:http://localhost/content/images/logo.png
缺少了application的名称!

再改改呗

public class CssRewriteUrlTransformWrapper : IItemTransform
{
    public string Process(string includedVirtualPath, string input)
    {
        return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
    }
}

使用

var myStyleBundle = new StyleBundle("~/Content/css")
.Include("~/Content/XXX/index.css", new CssRewriteUrlTransformWrapper())
.Include("~/Content/YYY/index.css", new CssRewriteUrlTransformWrapper());//new

bundles.Add(myStyleBundle);

Ref

https://learn.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification
https://stackoverflow.com/questions/32422223/mvc-bundling-and-relative-css-image-when-website-is-deployed-to-an-application
https://www.cnblogs.com/susilent/archive/2013/03/01/2939196.html

标签:MVC5,string,url,Minification,Content,var,new,NET,css
From: https://www.cnblogs.com/talentzemin/p/17853814.html

相关文章

  • .net抓取html文本中的链接集合
    publicstaticvoidGetListHtmlString(stringcontent,stringsearchStr,List<string>list){if(string.IsNullOrEmpty(content)||string.IsNullOrEmpty(searchStr))return;intthisIndex=0;while(true){intstartIndex=content.IndexOf(searchStr,......
  • .Net core 常见同步机制及其应用场景
    在.NETCore5中,提供了多种同步机制来处理多线程同步问题,下面分别介绍这些同步机制及其适用场景。lock关键字lock关键字是C#语言提供的一种基本的同步机制,可以用于保护临界区,确保多个线程对共享资源的访问互斥性。使用lock关键字时,需要指定一个对象作为锁,这个锁对象可......
  • log4net使用过程
    1.安装log4net,通过Nuget下载2.在AssemblyInfo.cs中添加[assembly:log4net.Config.XmlConfigurator(ConfigFile="log4net.config",ConfigFileExtension="config",Watch=true)]3.编写log4net.config,放在工程目录和exe目录<?xmlversion="1.0"?......
  • 平台工程时代的 Kubernetes 揭秘:2023年生产状况报告深度剖析
    Kubernetes在生产环境中的复杂性已经成为常态,在2023年这个平台工程盛行的时代,容器管理的最大亮点可能在于其灵活性,然而在运维政策和治理等方面仍然存在诸多挑战。八年过去了,在生产环境中使用Kubernetes仍然需要面临许多挑战。 SpectroCloud刚刚与DimensionalResearch合......
  • ConfigureAwait in .NET8
    ConfigureAwaitin.NET8ConfigureAwait(true)和ConfigureAwait(false)首先,让我们回顾一下原版ConfigureAwait的语义和历史,它采用了一个名为continueOnCapturedContext的布尔参数。当对任务(Task、Task<T>、ValueTask或ValueTask<T>)执行await操作时,其默认行为是捕获“上......
  • 在.net中使用AutoMapper进行对象映射,对象相互转,简单方便
    AutoMapper是一种对象映射工具,它可以帮助我们将不同类型的数据对象之间进行相互转换。在.NET中,我们可以使用AutoMapper库来简化数据对象之间的映射操作,从而提高代码的可读性和可维护性。一、AutoMapper的安装和基本使用安装AutoMapper首先,我们需要在项目中安装AutoMapper库。......
  • .net 温故知新【13】:Asp.Net Core WebAPI 缓存
    一、缓存缓存指在中间层中存储数据的行为,该行为可使后续数据检索更快。从概念上讲,缓存是一种性能优化策略和设计考虑因素。缓存可以显著提高应用性能,方法是提高不常更改(或检索成本高)的数据的就绪性。二、RFC9111在最新的缓存控制规范文件RFC9111中,详细描述了浏览器缓存和服务......
  • 掌握VB.net编程技巧,轻松打造Windows应用
    为了温故而知新,本博客旨在记录我学习VB.net编程的过程,分享基础知识和实用技巧,帮助有需要的朋友轻松入门VB.net编程。无论您是想开发Windows平台上的应用程序,还是想在.NET生态系统中展现创造力和创新精神,本文都将为您提供宝贵的指导。VB.net是一种易学易用的编程语言,它基于Microso......
  • .Net Core MVC超大文件上传
    后端控制器://用于保存的文件夹staticreadonlystringuploadFolder="UploadFolder";//目录分隔符,兼容不同系统staticreadonlychardirSeparator=Path.DirectorySeparatorChar;stringGetTmpChunkDir(stringfileName)=>HttpContext.Session.TryGet......
  • netty服务端加解密
    参考链接:https://www.cnblogs.com/silyvin/articles/11827030.html一、解密1、自定义解密类importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandlerContext;importio.netty.handler.codec.ByteToMessageDecoder;impor......