我已经将ASP.NET Web API CacheOutput库用于我的web.net的asp.net项目,它工作正常,但是我有一个POST方法的另一个控制器,我想从该控制器使我的缓存无效。
[AutoInvalidateCacheOutput]
public class EmployeeApiController : ApiController
{
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)]
public IEnumerable<DropDown> GetData()
{
//Code here
}
}
public class EmployeesController : BaseController
{
[HttpPost]
public ActionResult CreateEmployee (EmployeeEntity empInfo)
{
//Code Here
}
}
我希望在员工控制器中添加\ update时使Employees Cache无效。
这有点棘手,但你可以用这种方式得到它:
1.在您的WebApiConfig上:
// Registering the IApiOutputCache.
var cacheConfig = config.CacheOutputConfiguration();
cacheConfig.RegisterCacheOutputProvider(() => new MemoryCacheDefault());
我们需要它来从GlobalConfiguration.Configuration.Properties获取IApiOutputCache,如果我们让默认属性的设置发生,那么在MVC BaseController请求中不存在IApiOutputCache的属性。
2.创建WebApiCacheHelper类:
using System;
using System.Web.Http;
using WebApi.OutputCache.Core.Cache;
using WebApi.OutputCache.V2;
namespace MideaCarrier.Bss.WebApi.Controllers
{
public static class WebApiCacheHelper
{
public static void InvalidateCache<T, U>(Expression<Func<T, U>> expression)
{
var config = GlobalConfiguration.Configuration;
// Gets the cache key.
var outputConfig = config.CacheOutputConfiguration();
var cacheKey = outputConfig.MakeBaseCachekey(expression);
// Remove from cache.
var cache = (config.Properties[typeof(IApiOutputCache)] as Func<IApiOutputCache>)();
cache.RemoveStartsWith(cacheKey);
}
}
}
3.然后,从EmployeesController.CreateEmployee操作中调用它:
public class EmployeesController : BaseController
{
[HttpPost]
public ActionResult CreateEmployee (EmployeeEntity empInfo)
{
// your action code Here.
WebApiCacheHelper.InvalidateCache((EmployeeApiController t) => t.GetData());
}
}