ASP.NET OutputCache
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 OutputCache 功能。这种强大的缓存机制通过存储页面输出来提高应用程序性能。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。OutputCache 通过提供缓存内容来减少服务器负载。
基本定义
ASP.NET 中的 OutputCache 存储页面或用户控件的渲染输出。当后续请求到达时,会提供缓存内容而不是重新处理。
这显著提高了响应时间并减少了服务器资源使用。对于不经常更改但请求频率很高的内容尤其有用。
OutputCache 可以在不同级别进行配置:页面、控件或操作。它支持多种缓存位置:服务器、客户端或两者兼有。缓存持续时间可配置,单位为秒。
ASP.NET OutputCache 示例
以下示例演示了在 ASP.NET Core MVC 应用程序中使用 OutputCache。我们将缓存一个产品列表页面 60 秒。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("ProductCache", builder =>
{
builder.Expire(TimeSpan.FromSeconds(60));
builder.SetVaryByQuery("category");
});
});
var app = builder.Build();
app.UseOutputCache();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这会设置具有自定义缓存策略的 OutputCache 中间件。该策略定义了 60 秒的到期时间,并根据“category”查询参数变化缓存。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;
public class ProductsController : Controller
{
private static List<Product> _products = new()
{
new Product(1, "Laptop", "Electronics"),
new Product(2, "Chair", "Furniture"),
new Product(3, "Smartphone", "Electronics"),
new Product(4, "Table", "Furniture")
};
[OutputCache(PolicyName = "ProductCache")]
public IActionResult Index(string category)
{
var filteredProducts = string.IsNullOrEmpty(category)
? _products
: _products.Where(p => p.Category == category).ToList();
ViewBag.LastGenerated = DateTime.Now.ToString("HH:mm:ss");
return View(filteredProducts);
}
}
public record Product(int Id, string Name, string Category);
控制器操作通过使用我们的“ProductCache”策略的 OutputCache 属性进行装饰。该操作会在提供类别时按类别过滤产品。
@model List<Product>
<h2>Product List</h2>
<p>Last generated: @ViewBag.LastGenerated</p>
<div class="categories">
<a href="/Products">All</a>
<a href="/Products?category=Electronics">Electronics</a>
<a href="/Products?category=Furniture">Furniture</a>
</div>
<ul>
@foreach (var product in Model)
{
<li>@product.Name - @product.Category</li>
}
</ul>
视图显示产品列表以及生成时间。时间戳有助于验证缓存是否正常工作(在缓存持续时间内不会改变)。
当您运行此应用程序并导航到 /Products 时,该页面将被缓存 60 秒。缓存将为不同的类别存储不同的版本。
OutputCache 显著提高了常用页面的性能。该示例展示了如何通过查询参数变化来实现基本缓存。
来源
Microsoft ASP.NET OutputCache 文档
在本文中,我们探讨了 ASP.NET 8 中的 OutputCache 功能。这种强大的缓存机制可以显著提高应用程序的性能。