如何在asp.net MVC 中gzip 内容? [英] how to gzip content in asp.net MVC?

查看:24
本文介绍了如何在asp.net MVC 中gzip 内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何压缩asp.net mvc应用程序发送的输出??

how to compress the output send by an asp.net mvc application??

推荐答案

这是我使用的(截至目前):

Here's what i use (as of this monent in time):

using  System.IO.Compression;

public class CompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted)) return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();
        var response = filterContext.HttpContext.Response;

        if (encodingsAccepted.Contains("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
        else if (encodingsAccepted.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
    }
}

在控制器中的使用:

[Compress]
public class BookingController : BaseController
{...}

还有其他变体,但这很有效.(顺便说一句,我在我的 BaseController 上使用 [Compress] 属性来保存整个项目中的重复,而以上是在一个控制器一个控制器的基础上进行的.

there are other varients, but this works quite well. (btw, i use the [Compress] attribute on my BaseController to save duplication across the project, whereas the above is doing it on a controller by controller basis.

如上段所述.为了简化使用,您还可以在 BaseController 本身中包含 [Compress] oneshot,从而每个继承的子控制器默认访问该功能:

as mentioned in the para above. to simplify usage, you can also include [Compress] oneshot in the BaseController itself, thereby, every inherited child controller accesses the functionality by default:

[Compress]
public class BaseController : Controller
{...}

这篇关于如何在asp.net MVC 中gzip 内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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