c# - 如何使用 Asp.Net Core 2.2 在子域上服务器图像?

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

最佳答案

我将任何对性能至关重要的东西放入我的中间件中。在 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 方法中,您必须使用中间件:

app.UseMiddleware<Middle>();

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

您需要确保这个中间件首先运行,这样它就可以阻止任何在它之后运行的东西。当然,除非您希望对静态内容运行某种身份验证

关于c# - 如何使用 Asp.Net Core 2.2 在子域上服务器图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58664642/

相关文章:

c# - 如何让用户创建任务并设置任务运行的时间?

mongodb - 带有MongoDB标识的ASP.NET Core 2.0

asp.net - 在 IIS 上托管 Asp.Net Core 2

azure - 从 VS 发布到 Azure 时无法更改目标运行时

asp.net-core-2.0 - 使用 SAML 2.0 作为 SSO 的外部身份提供者的身份服务器 4

c# - 我需要帮助将 VB.Net Linq 转换为 C# Linq

c# - 为什么我不能将 long 的 object-var 转换为 double?

c# - 在 Xamarin/Visual Studio 中构建的 native iOS 应用程序打开然后立即关闭

c# - 你能在asp.net-mvc中强制删除(页面和partialView)OutputCache吗

asp.net-core - 如何在 Fable Elmish SPA 中处理从后端重定向到身份验证提供程序