在C# ASP.NET中,有多種方法可以實現緩存機制。以下是一些建議:
System.Runtime.Caching
命名空間。示例代碼:
using System.Runtime.Caching;
public class CacheManager
{
private static MemoryCache _cache = MemoryCache.Default;
public object Get(string key)
{
return _cache.Get(key);
}
public void Add(string key, object value, DateTimeOffset absExpiration)
{
_cache.Add(key, value, absExpiration);
}
public void Remove(string key)
{
_cache.Remove(key);
}
}
示例代碼(使用Redis):
using Microsoft.AspNetCore.Caching.StackExchangeRedis;
using System.Threading.Tasks;
public class DistributedCacheManager
{
private readonly IDistributedCache _cache;
public DistributedCacheManager(IDistributedCache cache)
{
_cache = cache;
}
public async Task<string> GetAsync(string key)
{
return await _cache.GetStringAsync(key);
}
public async Task SetAsync(string key, string value, TimeSpan expiration)
{
await _cache.SetStringAsync(key, value, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiration
});
}
public async Task RemoveAsync(string key)
{
await _cache.RemoveAsync(key);
}
}
[OutputCache]
屬性。示例代碼(頁面級緩存):
using System.Web.UI;
[OutputCache(Duration = 60, VaryByParam = "none")]
public partial class Index : Page
{
// 頁面代碼
}
示例代碼(控制器級緩存):
using System.Web.Mvc;
public class HomeController : Controller
{
[OutputCache(Duration = 60, VaryByParam = "none")]
public ActionResult Index()
{
// 控制器代碼
return View();
}
}
這些緩存策略可以根據項目需求進行選擇和組合使用。