使用ASP.NET Core 3.1,我创建了一个中间件,如下所示:
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 = await sitemapService.GetAsync();
context.Response.ContentType = "application/xml";
context.Response.Headers.Add("Cache-Control", "public,max-age=20");
await context.Response.WriteAsync(sitemap.Build(), Encoding.UTF8);
} else {
await _next(context);
}
}
}
当我在浏览器中访问“ sitemap.xml”时,得到的响应具有正确的内容。
但是当我在接下来的20秒内再次访问它时,代码将再次执行。
我正在添加“ Cache-Control”标头,并检查了它是否在响应中。
为什么再次执行代码?
如果不想依靠HTTP缓存,则可以使用ASP.NET缓存,例如内存缓存。我整理了一个与我使用的类似的小例子。可能有帮助。
public class SitemapController : Controller
{
const string SITEMAP_CACHE_KEY = "SitemapNodesCacheKey";
readonly IMemoryCache cache;
public SitemapController(IMemoryCache cache)
{
this.cache = cache;
}
/// <summary>
/// Returns sitemap of this web.
/// Handles caching etc.
/// </summary>
/// <returns></returns>
protected string GetSitemap()
{
//Cache not found
if (!cache.TryGetValue(SITEMAP_CACHE_KEY, out var cacheEntry))
{
cacheEntry = "SOME CACHE TEXT/STRUCTURE HERE";
//Set cache options
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(8))
.SetAbsoluteExpiration(TimeSpan.FromHours(24));
//Save data in cache
cache.Set(SITEMAP_CACHE_KEY, cacheEntry, cacheEntryOptions);
}
return cacheEntry as string;
}
[HttpPost("/sitemap/update")]
public IActionResult UpdateSitemap()
{
cache.Remove(SITEMAP_CACHE_KEY);
return Ok();
}
[Route("/sitemap.xml")]
public IActionResult SitemapFile()
{
return Content(GetSitemap(), "text/xml");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句