【问题标题】:How to invalidate Web API cache from another Controller(ASP.NET Web API CacheOutput Library)如何使另一个控制器的 Web API 缓存无效(ASP.NET Web API CacheOutput 库)
【发布时间】:2015-02-05 21:54:36
【问题描述】:

我已经将 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
    }
}

当员工控制器中有添加\更新时,我想使员工缓存无效。

【问题讨论】:

  • 我不确定,但 [NoCache] 属性可以提供帮助。
  • 我想要缓存,但只想在员工控制器发生变化时失效

标签: asp.net-mvc asp.net-web-api2 outputcache asp.net-cache


【解决方案1】:

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

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());
    }
}

【讨论】:

  • 谢谢,但我使用的是 ASP.Net 4.0,而 WebApi.OutputCache.V2 仅在 ASP.net 4.5 中可用,您对使用 ASP.Net 4.0 有其他建议吗?或者我必须将我的解决方案升级到 asp.net 4.5
  • 我不知道,我从未将 WebApi.OutputCache 与 ASP .NET 4.0 一起使用。
  • 似乎您的解决方案适用于 4.5,因为它没有解决我的问题,但接受作为答案希望对其他人有所帮助。
  • 太棒了!正是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 2013-01-26
  • 2013-06-23
相关资源
最近更新 更多