Asp.Net Core服务端处理请求过来的压缩格式

之前是直接传没有经过压缩的文件字节,有时文件过大的话,可能占宽带就多,宽带流量都是钱。后来有个想法,在客户端把文件进行压缩,把压缩的文件流发给服务端进行解压。

1,先修改项目中Startup.cs文件中ConfigureServices()方法中的代码:

复制代码
//注册压缩响应
services.AddResponseCompression((options) =>
{
	options.EnableForHttps = true;
	options.Providers.Add<Microsoft.AspNetCore.ResponseCompression.GzipCompressionProvider>();
});

2 ,先修改项目中Startup.cs文件中Configure(IApplicationBuilder app, IWebHostEnvironment env)方法中的代码:

复制代码
//使用gzip压缩
app.UseResponseCompression();

3,在控制层处理传过来压缩文件进行处理。

复制代码
var formFiles = (Microsoft.AspNetCore.Http.FormFileCollection)formCollection.Files;
byte[] bytes = new byte[] { };
foreach (var item in formFiles)
{
	bytes = DeZip(item.OpenReadStream());
}
string html2 = System.Text.Encoding.UTF8.GetString(bytes);


public static byte[] DeZip(Stream stream)
{
	byte[] buffer2 = new byte[1024];
	int length;

	using (var gz = new GZipStream(stream, CompressionMode.Decompress))
	{
		using (MemoryStream msTemp = new MemoryStream())
		{
			while ((length = gz.Read(buffer2, 0, buffer2.Length)) != 0)
			{
				msTemp.Write(buffer2, 0, length);
			}

			return msTemp.ToArray();
		}
	}

}
相关推荐
唐青枫17 小时前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62521 小时前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021121 小时前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠2 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫4 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech4 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf6 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6256 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech6 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
网络研究院7 天前
2026年网络安全
网络·安全·法律·法规·趋势·发展