我需要在呈现给用户之前更改完整的html响应流(使用html解析). 哪里/何时是最后一次机会? 恕我直言,在ASP.NET MVC环境中更改 HTML响应的更好方法是使用动作过滤器. 这是用于压缩输出的动
哪里/何时是最后一次机会? 恕我直言,在ASP.NET MVC环境中更改 HTML响应的更好方法是使用动作过滤器.
这是用于压缩输出的动作过滤器的示例:
public class CompressFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequestBase request = filterContext.HttpContext.Request; string acceptEncoding = request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) return; acceptEncoding = acceptEncoding.ToUpperInvariant(); HttpResponseBase response = filterContext.HttpContext.Response; if (acceptEncoding.Contains("GZIP")) { response.AppendHeader("Content-encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); } else if (acceptEncoding.Contains("DEFLATE")) { response.AppendHeader("Content-encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); } } }
你可以在你的动作方法上使用它:
[CompressFilter] // Minifies, compresses JavaScript files and stores the response in client (browser) cache for a day public JavaScriptResult GetJavaScript(string jsPath)
HTH