我如何使用Asp.Net Core 2.2在子域中托管图像?

问题描述 投票:1回答:1

我在Asp.Net Core 2.2框架的顶部有一个使用C#编写的应用程序。

该应用旨在显示大量图像。我正在尝试通过使用无Cookie的子域来减少从服务器请求图像时的流量,从而提高应用程序的性能。

当前,我使用UseStaticFiles扩展名,以允许使用以下URL https://example.com/photos/a/b/c/1.jpg访问我的照片。相反,现在我想更改URL以使用https://photos.example.com/a/b/c/1.jpg投放这些照片。这是我现在使用UseStaticFiles扩展名提供图像的方式

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = blobFileProvider,
    RequestPath = "/photos",
    OnPrepareResponse = ctx =>
    {
        const int durationInSeconds = 3600 * 72;

        ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds;
    }
});

[我确定可以为图像创建第二个应用程序,但是如何使用Asp.Net Core 2.2框架在photos.example.com子域上提供图像而不需要第二个正在运行的应用程序?

c# asp.net-core asp.net-core-2.0 asp.net-core-2.2
1个回答
0
投票

我将任何对性能有重要要求的内容放入我的MiddleWare。在MiddleWare中,您可以检查主机和/或路径,并将文件直接写入响应流并缩短返回值。

您只需要添加一个看起来像这样的MiddleWare类:

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

public class Middle
{
  private readonly RequestDelegate _next;

  public Middle(RequestDelegate next)
  {
    _next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    string req_path = context.Request.Path.Value;
    string host = context.Request.Host.Value;

    if (host.StartsWith("photos.")) {
      context.Response.Clear();
      context.Response.StatusCode = 200;
      context.Response.ContentType = "<Image Type>";
      await context.Response.SendFileAsync(<file path>);
      return;
    }
    else {
      await _next.Invoke(context);
    }
  }
}

然后在Startup.cs的Configure方法中,您必须使用MiddleWare:

app.UseMiddleware<Middle>();

[如何使服务器将子域和裸域视为同一应用程序,取决于您所使用的服务器。在IIS中,您可以只创建两个指向相同应用程序并使用相同应用程序池的不同站点(至少在旧的.NET中有效)。您也许也可以给映像站点一个唯一的端口号,因为我认为cookie特定于主机端口组合。

© www.soinside.com 2019 - 2024. All rights reserved.