2014-12-08 39 views
11

我已經使用ASP.NET Web API CacheOutput庫爲我的asp.net項目的Web API,它工作正常,但有另一個控制器我有一個POST方法,我想從該控制器中取消緩存。如何從另一個控制器(ASP.NET Web API CacheOutput庫)中使Web API緩存失效

[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 
    } 
} 

我想在僱員控制器中添加\更新時使員工緩存失效。

+0

我不知道,但[NoCache的]屬性可以幫助。 – 2014-12-11 06:58:36

+0

我想要緩存,但只是想失效時,員工控制器的變化 – Suresh 2014-12-11 08:06:10

回答

10

這是有點麻煩,但你可以通過這種方式得到它:

1.在WebApiConfig:

// Registering the IApiOutputCache.  
var cacheConfig = config.CacheOutputConfiguration(); 
cacheConfig.RegisterCacheOutputProvider(() => new MemoryCacheDefault()); 

我們需要的是從GlobalConfiguration得到IApiOutputCache。 Configuration.Properties,如果我們讓默認屬性的設置發生,具有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()); 
    } 
} 
+0

謝謝,但我使用ASP.Net 4.0和WebApi.OutputCache.V2只能在ASP.net 4.5中有沒有任何其他建議與ASP.Net 4.0一起工作?或者我必須將我的解決方案升級到asp.net 4.5 – Suresh 2014-12-11 13:12:45

+0

我不知道,我從來沒有在ASP .NET 4.0中使用過WebApi.OutputCache。 – giacomelli 2014-12-11 13:22:22

+0

似乎你的解決方案將適用於4.5,因爲它不能解決我的問題,但接受作爲答案的希望,這將有助於其他人。 – Suresh 2014-12-15 17:05:35