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();
		}
	}

}
相关推荐
Artech1 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf2 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6252 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech2 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
网络研究院3 天前
2026年网络安全
网络·安全·法律·法规·趋势·发展
酣大智3 天前
ARP代理--工作原理
运维·网络·arp·arp代理
treesforest3 天前
AI安全系统如何识别异常访问?IP风险识别正在成为关键能力
网络·人工智能·tcp/ip·安全·web安全
shushangyun_3 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
2601_961845153 天前
粉笔行测题库|系统班|刷题
网络·百度·微信·微信公众平台·facebook·新浪微博
程序猿阿伟3 天前
《Chrome离线扩展安装的底层逻辑与场景落地指南》
服务器·网络·chrome