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

时间:2019-11-01 19:12:12

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-2.2

我在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子域上提供图像而又不需要第二个正在运行的应用程序?

2 个答案:

答案 0 :(得分:1)

我将使用MapWhen方法分支请求管道。然后按照您的步骤应用<dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-jdbc</artifactId> <version>3.1.0.3.1.0.0-78</version> </dependency>

最终结果将如下所示

UseStaticFiles

答案 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是特定于主机端口组合的。

您将要确保该中间件先运行,这样它就可以阻止运行后的任何事情。除非您当然要为静态内容运行某种身份验证

相关问题