缩小操作过滤器属性在ASP.NET MVC [英] Minify Action Filter Attribute in ASP.NET MVC

查看:96
本文介绍了缩小操作过滤器属性在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回大量的动态JavaScript的(被服务一次,客户端)的控制器操作,我已经启用的GZip COM pression。有一件事我想要做的是读取执行结果流并把它应用JS缩小。

I have a controller action that returns a large amount of dynamic JavaScript (gets served once to the client) and I already have GZip compression enabled. One thing I'd like to do is read the executed result stream and apply JS minification on it.

是否有可能做到这一点使用操作过滤器属性。我想我的问题归结为 - 假设我minifier采用JavaScript的一个字符串是有办法拉执行结果作为串出视图(View).ExecuteResult(ControllerContext)

Is it possible to do this using an Action Filter Attribute. I think my question boils down to - Assuming my minifier takes a string of JavaScript is there a way to pull the executed result as a string out of View(view).ExecuteResult(ControllerContext) ?

推荐答案

<击>我觉得对于.NET的YUI的COM pressor会做正是你需要的。

I think the YUI Compressor for .NET will do exactly what you need.

的http://yuicom$p$pssor.$c$cplex.com/

修改:以上是错误的,因为我误解的问题。下面的code将安装响应滤波器允许你操纵的输出,在这种情况下,它只是删除换行符。

EDIT: Above is wrong as I misread the question. The code below will install a response filter allowing you to manipulate the output, in this case it just removes newline characters.

希望这有助于。

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

这篇关于缩小操作过滤器属性在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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