63 lines
2.3 KiB
C#
63 lines
2.3 KiB
C#
using System.IO;
|
|
using System.IO.Compression;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Web.Http;
|
|
|
|
namespace DeviceRepair.Api.Models
|
|
{
|
|
public class CompressedContentResult<T> : IHttpActionResult
|
|
{
|
|
private readonly T _value;
|
|
private readonly HttpRequestMessage _request;
|
|
private readonly ApiController _controller;
|
|
|
|
public CompressedContentResult(T value, HttpRequestMessage request, ApiController controller)
|
|
{
|
|
_value = value;
|
|
_request = request;
|
|
_controller = controller;
|
|
}
|
|
|
|
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
|
|
{
|
|
var response = _controller.Request.CreateResponse(HttpStatusCode.OK, _value, _controller.Configuration.Formatters.JsonFormatter);
|
|
|
|
// 检查客户端是否接受 GZIP 压缩
|
|
var acceptsEncoding = _request.Headers.AcceptEncoding;
|
|
var gzipSupported = acceptsEncoding.Any(x => x.Value.Contains("gzip"));
|
|
|
|
if (gzipSupported)
|
|
{
|
|
var originalContent = response.Content.ReadAsStringAsync().Result; // 注意:这里同步读取可能会导致问题,但在示例中为了简化
|
|
byte[] compressedContent = CompressString(originalContent);
|
|
|
|
var compressedStream = new MemoryStream(compressedContent);
|
|
var compressedContentResult = new StreamContent(compressedStream);
|
|
compressedContentResult.Headers.ContentType = response.Content.Headers.ContentType;
|
|
compressedContentResult.Headers.ContentEncoding.Add("gzip");
|
|
|
|
response.Content = compressedContentResult;
|
|
}
|
|
|
|
return Task.FromResult(response);
|
|
}
|
|
|
|
private byte[] CompressString(string str)
|
|
{
|
|
byte[] buffer = Encoding.UTF8.GetBytes(str);
|
|
var memoryStream = new MemoryStream();
|
|
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
|
|
{
|
|
gZipStream.Write(buffer, 0, buffer.Length);
|
|
}
|
|
|
|
memoryStream.Position = 0;
|
|
return memoryStream.ToArray();
|
|
}
|
|
}
|
|
} |