首页 > 解决方案 > 如何在 Asp.Net Core 中间件中缓存响应?

问题描述

我在 ASP.NET Core 3.1 中创建了一个中间件,以从 route 返回 XML Sitemap /sitemap.xml

public class SitemapMiddleware {

  private readonly RequestDelegate _next;

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

  public async Task InvokeAsync(HttpContext context, ISitemapService sitemapService) {

  if (context.Request.Path.StartsWithSegments("/sitemap.xml)) {

    Sitemap sitemap = sitemapService.GetSitemap();

    context.Response.ContentType = "application/xml";

    await context.Response.WriteAsync(sitemap.ToString(), Encoding.UTF8);

  } else {

    await _next(context);
    
  }

} 

我将其注册如下:

public static class SitemapMiddlewareExtensions {

  public static IApplicationBuilder UseSitemap(this IApplicationBuilder builder) {

    return builder.MapWhen(x => x.Request.Path.StartsWithSegments("/sitemap.xml"), 
      x => x.UseMiddleware<SitemapMiddleware>(route));

  } 

}

问题

如果缓存的响应超过 24 小时,如何缓存中间件的响应并调用 SitemapService?

标签: asp.net-coreasp.net-core-3.1

解决方案


推荐阅读