You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function中GZipStream加载System.IO.Compression程序集失败求助

问题:Azure Function使用GZipStream解压时抛出程序集加载失败错误

问题详情

  • 本地运行基于.NET7的Azure Function,从Redis获取值后使用GZipStream解压时抛出错误:

    FAILED- 无法加载文件或程序集“System.IO.Compression, Version=7.0.0.0, Culture=neutral, PublicKeyToken=TOKEN”。系统找不到指定的文件。

  • 已在代码顶部添加using System.IO.Compression;语句,且该程序集存在于Microsoft.NETCore.App框架依赖的本地路径C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\7.0.10\ref\net7.0\System.IO.Compression.dll,但未出现在解决方案的NuGet包列表中,项目重新生成无编译错误。
  • 疑问:是否可以显式引用该dll?另外错误并非在GZipStream实例化的代码行抛出,而是调用包含该行的GetContextFromRedis方法时触发。
  • 函数用途:接收HTML字符串或Redis键,返回生成的PDF字节数组。

相关代码

using IronPdf;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using ExecutionContext = Microsoft.Azure.WebJobs.ExecutionContext;

namespace NameSpace
{
    public static class Print
    {
        [FunctionName("PrintPdf")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "PDF/{GUID}")] HttpRequest req, string GUID, ILogger log, ExecutionContext context)
        {
            string result = "OK";
            log.LogInformation("Rendering PDF " + GUID);
            PdfDocument doc;

            //Get from redis
            var html = await GetContextFromRedis("keyUsedToGetValue");

            string reportHTML = "<!DOCTYPE html>\r\n<html>\r\n<body>\r\n\r\n<h1>Report</h1>\r\n\r\n<p>" + html + "</p>\r\n\r\n</body>\r\n</html>";
            doc = renderer.RenderHtmlAsPdf(reportHTML);
            string Filename = "report.pdf";

            log.LogInformation("finished rendering pdf...");
            return new FileContentResult(doc.BinaryData, "application/pdf") { FileDownloadName = Filename };
        }

        private static async Task<string> GetContextFromRedis(string Key)
        {
            try
            {
                Lazy<Task<ConnectionMultiplexer>> lazyConnection = new Lazy<Task<ConnectionMultiplexer>>(async () =>
                {
                    string Address = "address",
                        Password = "password";
                    var cacheConnection = $"{connection}";
                    return await ConnectionMultiplexer.ConnectAsync(cacheConnection).ConfigureAwait(false);
                });
                Task<ConnectionMultiplexer> Connection = lazyConnection.Value;

                IDatabase cache = (await Connection.ConfigureAwait(false)).GetDatabase();
                var compressedString = await cache.StringGetAsync(Key).ConfigureAwait(false);

                #region Decompress String

                byte[] gZipBuffer = Convert.FromBase64String(compressedString);
                using var memoryStream = new MemoryStream();

                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                await using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                //compressedString = Encoding.UTF8.GetString(buffer);

                #endregion

                return compressedString;
                //return HttpUtility.UrlDecode(compressedString);
            }
            catch
            {
                return "";
            }
        }
    }
}

解决方案

1. 显式安装NuGet包(推荐)

不要直接引用本地dll,通过NuGet包管理器安装System.IO.Compression包,选择与.NET7匹配的版本(如7.0.0)。Azure Function的宿主环境对框架自带的程序集引用支持有限,显式安装NuGet包能确保运行时正确加载依赖。

2. 确认项目配置

  • 检查项目文件(.csproj),确保目标框架和Azure函数版本配置正确:
    <PropertyGroup>
      <TargetFramework>net7.0</TargetFramework>
      <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    </PropertyGroup>
    
  • 确保本地运行的Azure Function Core Tools为v4.x版本,该版本兼容.NET7。

3. 修正代码缺陷

  • 实例化IronPdf渲染器:在Run方法中添加var renderer = new ChromePdfRenderer();,否则renderer.RenderHtmlAsPdf会抛出未定义错误。
  • 修复Redis连接字符串:将cacheConnection = $"{connection}";替换为实际的连接字符串,比如$"{Address},password={Password}"。
  • 修正解压逻辑返回值:将return compressedString;改为return Encoding.UTF8.GetString(buffer);,同时添加using System.Text;引用。
  • 建议移除空catch块,添加日志记录以排查异常细节。

4. 清理重建项目

  • 删除项目的bin和obj文件夹,重新构建项目,确保所有依赖项正确复制到输出目录。
  • 重启Azure Function Core Tools,避免缓存导致的程序集加载异常。

内容的提问来源于stack exchange,提问作者redbullPoweredDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:55:58