Asp.net-Mvc
如何使另一個控制器的 Web API 記憶體無效(ASP.NET Web API CacheOutput 庫)
我已經將 ASP.NET Web API CacheOutput 庫用於我的 web API 的 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 } }當員工控制器中有 add\update 時,我想使員工記憶體無效。
這有點棘手,但您可以通過以下方式獲得它:
1. 在您的 WebApiConfig 上:
// Registering the IApiOutputCache. var cacheConfig = config.CacheOutputConfiguration(); cacheConfig.RegisterCacheOutputProvider(() => new MemoryCacheDefault());我們將需要它來從 GlobalConfiguration.Configuration.Properties 獲取 IApiOutputCache,如果我們讓預設屬性設置發生,那麼帶有 IApiOutputCache 的屬性將不會存在於 MVC BaseController 請求中。
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()); } }