【发布时间】:2015-09-03 10:37:34
【问题描述】:
我已经编写了一个缓存类,但我很困惑如何在 MVC 的应用程序中使用它?
using System;
using System.Configuration;
using System.Runtime.Caching;
namespace ABC
{
public class InMemoryCache : ICache
{
protected ObjectCache Cache
{
get
{
return MemoryCache.Default;
}
}
/// Insert value into the cache using key, Value pairs
public void Add<T>(T o, string key)
{
if (o == null)
return;
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now.AddMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["CacheExpirationTime"]));
Cache.Add(new CacheItem(key, o), policy);
}
public void Update<T>(T o, string key)
{
if (Cache.Contains(key))
{
Cache[key] = o;
}
else
{
Add(o, key);
}
}
/// Remove item from cache
public void Remove(string key)
{
Cache.Remove(key);
}
/// Check for item in cache
public bool Exists(string key)
{
return Cache[key] != null;
}
public void Clear()
{
foreach (var item in Cache)
Remove(item.Key);
}
/// Retrieve cached item.Default(T) if item doesn't exist
public bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}
value = (T)Cache[key];
}
catch
{
value = default(T);
return false;
}
return true;
}
public T Get<T>(string key)
{
try
{
return (T)Cache[key];
}
catch
{
return default(T);
}
}
}
}
我有 BaseController,我在其中编写了 OnAuthentication()
//How can i use Caching here as it hits on every click made in application
protected override void OnAuthentication(AuthenticationContext filterContext)
{
Check.NotEmpty(SsoId, "Unable to determine your AmexWeb logon identity. Please contact the system administrator.");
var requestingUser = new RBACUser(SsoId, _sprocService);
//How can i use Caching here as it hits on every click made in application
UserPermissions = requestingUser.UserPermissions;
PermissionsMaster = requestingUser.PermissionsMaster;
var user = LoggedInUser = requestingUser.User;
if (user == null)
{
if (HttpContext.Session != null)
{
HttpContext.Session["User"] = null;
HttpContext.Session["UserName"] = null;
}
}
else
{
if (HttpContext.Session != null)
{
HttpContext.Session["User"] = user.ADSId;
HttpContext.Session["UserName"] = user.FullName;
}
_userId = user.UserId;
_regionCode = user.Segment.RegionCode;
}
}
【问题讨论】:
标签: c# asp.net-mvc-4 caching memorycache