12

我已经将 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 时,我想使员工缓存无效。

4

1 回答 1

12

这有点棘手,但您可以通过以下方式获得它:

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());
    }
}
于 2014-12-11T10:42:31.927 回答