我有一个在 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/