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

React前端+.NET后端(EF+Azure数据库)API数据加载缓慢排查与解决

React + .NET + Azure DB 页面加载慢问题排查与解决

问题现象

  • 技术栈:React前端搭配.NET后端,通过EF连接Azure数据库
  • 页面加载极慢,刷新后前端console.log("GETTING DATA FROM SERVER")立即输出,但API响应需数秒才返回
  • 曾怀疑数据库频繁通信导致问题,尝试将产品列表直接存储在API本地,加载速度无改善

问题定位

经排查,问题根源是数据库中每个产品实体存储了4张未压缩的原图数据,原创建产品代码直接将图片文件转为字节数组存入数据库:

public void CreateProduct(Product p)
{
    using (ApplicationDbContext context = new ApplicationDbContext())
    {
        if (p.MainImageFile != null)
        {
            using (var stream = new MemoryStream())
            {
                p.MainImageFile.CopyTo(stream);
                p.MainImageData = stream.ToArray();
            }
        }

        if (p.AdditionalImageFiles.Any())
        {
            foreach (var file in p.AdditionalImageFiles)
            {
                using (var stream = new MemoryStream())
                {
                    file.CopyTo(stream);
                    p.AdditionalImages.Add(stream.ToArray());
                }
            }
        }

        context.Products.Add(p);
        context.SaveChanges();
    }
}

解决方案

通过压缩图片数据大小解决问题,优化后的代码如下:

public void CreateProduct(Product p)
{
    using (ApplicationDbContext context = new ApplicationDbContext())
    {
        if (p.MainImageFile != null)
        {
            p.MainImageData = ResizeImage(p.MainImageFile);
        }

        if (p.AdditionalImageFiles.Any())
        {
            foreach (var file in p.AdditionalImageFiles)
            {
                var resizedImage = ResizeImage(file);
                p.AdditionalImages.Add(resizedImage);
            }
        }

        context.Products.Add(p);
        context.SaveChanges();
    }
}

private byte[] ResizeImage(IFormFile imageFile)
{
    using (var stream = new MemoryStream())
    {
        imageFile.CopyTo(stream);
        stream.Seek(0, SeekOrigin.Begin); // 重置流位置到起始处
        var image = SKBitmap.Decode(stream);

        // 计算缩放比例,保持宽高比
        int maxWidth = 1080; // 可自定义最大宽度
        double scale = Math.Min((double)maxWidth / image.Width, 1); // 确保不放大图片
        var newWidth = (int)(image.Width * scale);
        var newHeight = (int)(image.Height * scale);

        using (var resizedImage = image.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High))
        {
            if (resizedImage == null) return null; // 处理缩放失败情况

            using (var ms = new MemoryStream())
            {
                using (var skImage = SKImage.FromBitmap(resizedImage))
                using (var data = skImage.Encode(SKEncodedImageFormat.Png, 75)) // 调整图片质量
                {
                    data.SaveTo(ms);
                    return ms.ToArray();
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Руслан Василев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:13:24