写一个ActionFilter来实现GZIP:
CompressFilterAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.IO.Compression;
namespace MyMVC.ActionFilters
{
public classCompressFilterAttribute:ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContextfilterContext)
{
string acceptEncoding =filterContext.HttpContext.Request.Headers["Accept-Encoding"];
if (String.IsNullOrEmpty(acceptEncoding)) return;
var response = filterContext.HttpContext.Response;
acceptEncoding = acceptEncoding.ToUpperInvariant();
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);
}
}
}
}
在controller文件中
[CompressFilter]
public ActionResult Compress()
{
return this.View();
}
联系客服