簡體   English   中英

ASP.NET Core 5.0 使用修改后的響應提供靜態文件

[英]ASP.NET Core 5.0 serve static files with modified response

當使用高度或寬度參數從 Uploads 文件夾請求圖像時,它們必須自動縮小到所需的大小。 然而,無論我做什么,我都無法停止響應原始圖像的寫作。 如何修改靜態文件處理程序的響應?

在我的 Startup.cs 中,我有:

string uploadsDirPath = Path.GetFullPath("Uploads".TrimStart('~', '/'), env.ContentRootPath);
Directory.CreateDirectory(uploadsDirPath);

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(uploadsDirPath),
    RequestPath = new PathString("/Uploads"),
    ContentTypeProvider = fileExtensionProvider,
    OnPrepareResponse = async (context) =>
    {
        context.Context.Response.Headers[HeaderNames.CacheControl] = "public,must-revalidate,max-age=" + TimeSpan.FromDays(365).TotalSeconds;

        // Modify only images.
        if (context.Context.Response.ContentType.StartsWith("image/"))
        {
            int.TryParse(context.Context.Request.Query["width"], out int width);
            int.TryParse(context.Context.Request.Query["height"], out int height);

            if ((width == 0 && height == 0) || context.Context.Response.ContentType == "image/svg+xml" || context.Context.Response.ContentType == "image/gif")
                return;

            // SkiaSharp resize.
            using (var original = SKBitmap.Decode(context.File.PhysicalPath))
            {
                if ((width == 0 || width > original.Width) && (height == 0 || height > original.Height))
                    return;

                // Respect original ratio.
                if (width > 0)
                    height = original.Height * width / original.Width;
                else
                    width = original.Width * height / original.Height;

                using (var resized = original.Resize(new SKImageInfo(width, height), SKFilterQuality.High))
                {
                    if (context.Context.Request.Headers[HeaderNames.Accept].ToString().Contains("image/webp"))
                    {
                        var stream = resized.Encode(SKEncodedImageFormat.Webp, 80).AsStream();
                        context.Context.Response.ContentType = "image/webp";
                        context.Context.Response.Body = stream;
                        context.Context.Response.ContentLength = stream.Length;
                        // not working.
                        await context.Context.Response.CompleteAsync();
                        return;
                    }
                }
            }
        }
    }
});

您正在嘗試使用靜態文件中間件來提供動態文件。 您不能修改靜態內容,因為它是靜態的。

編寫您自己的中間件,將PhysicalFileProvider和您擁有的縮減代碼結合起來。

有一些關於此的博客,例如https://www.paddo.org/asp-net-core-image-resizing-middleware/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM