在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();
}
}
这些缓存策略可以根据项目需求进行选择和组合使用。