csharp [C#] [MVC]缩小内联脚本和样式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp [C#] [MVC]缩小内联脚本和样式相关的知识,希望对你有一定的参考价值。
public class MinifyInlineScriptsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var originalFilter = filterContext.HttpContext.Response.Filter;
if(originalFilter != null) filterContext.HttpContext.Response.Filter = new MinifyStream(originalFilter);
base.OnActionExecuting(filterContext);
}
private class MinifyStream : MemoryStream
{
private readonly Stream _responseStream;
public MinifyStream(Stream stream)
{
_responseStream = stream;
}
public override void Write(byte[] buffer, int offset, int count)
{
string html = Encoding.UTF8.GetString(buffer);
var sb = new StringBuilder(html);
MinifyScripts(sb);
MinifyStyles(sb);
buffer = Encoding.UTF8.GetBytes(sb.ToString());
_responseStream.Write(buffer, offset, buffer.Length);
}
private void MinifyScripts(StringBuilder html)
{
var regex = new Regex("<script[^/>]*>(?<content>.*?)</script>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var matches = regex.Matches(html.ToString());
foreach (Match match in matches)
{
var content = match.Groups["content"];
if (content != null && content.Success && !String.IsNullOrWhiteSpace(content.Value))
{
var minifier = new Minifier();
var minifiedJs = minifier.MinifyJavaScript(content.Value);
html.Replace(content.Value, minifiedJs);
}
}
}
private void MinifyStyles(StringBuilder html)
{
var regex = new Regex("<style[^/>]*>(?<content>.*?)</style>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var matches = regex.Matches(html.ToString());
foreach (Match match in matches)
{
var content = match.Groups["content"];
if (content != null && content.Success && !String.IsNullOrWhiteSpace(content.Value))
{
var minifier = new Minifier();
var minifiedCss = minifier.MinifyStyleSheet(content.Value);
html.Replace(content.Value, minifiedCss);
}
}
}
}
}
以上是关于csharp [C#] [MVC]缩小内联脚本和样式的主要内容,如果未能解决你的问题,请参考以下文章
csharp 使用内联css / javascript为MVC C#缩小HTML作为ActionFilterAttribute
csharp 测试C#内联方法(框架4.5)
csharp C#:JsonResult替代ASP.NET MVC。
csharp 具有匿名类型c#的.net mvc json结果
csharp 在MVC项目C#中验证文件扩展名(示例中为.pdf)。
Akima 插值和样条插值的C语言源代码,要有注释。