我有一个控制器操作,返回大量动态JavaScript(一次服务到客户端),我已经启用了GZip压缩。我想做的一件事是阅读执行的结果流并在其上应用JS缩小。
是否可以使用动作过滤器属性执行此操作。我想我的问题归结为 - 假设我的minifier接受了一串JavaScript,有没有办法将执行结果作为View(view).ExecuteResult(ControllerContext)
的字符串拉出来?
答案 0 :(得分:4)
我认为YUI Compressor for .NET将完全满足您的需求。
<击> http://yuicompressor.codeplex.com/ 击>
编辑:上面错了,因为我误解了这个问题。下面的代码将安装一个响应过滤器,允许您操作输出,在这种情况下,它只是删除换行符。
希望这有帮助。
[HandleError]
public class HomeController : Controller
{
[Minify]
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
public class Minify : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//You can check if the content type is CSS/JS here and prevent the filter running on HTML pages
filterContext.HttpContext.Response.Filter = new MinifyFilter(filterContext.HttpContext.Response.Filter);
base.OnActionExecuting(filterContext);
}
}
public class MinifyFilter : MemoryStream
{
private StringBuilder outputString = new StringBuilder();
private Stream outputStream = null;
public MinifyFilter(Stream outputStream)
{
this.outputStream = outputStream;
}
public override void Write(byte[] buffer, int offset, int count)
{
outputString.Append(Encoding.UTF8.GetString(buffer));
}
public override void Close()
{
//Call the minifier here, your data is in outputString
string result = outputString.ToString().Replace(Environment.NewLine, string.Empty);
byte[] rawResult = Encoding.UTF8.GetBytes(result);
outputStream.Write(rawResult, 0, rawResult.Length);
base.Close();
outputStream.Close();
}
}