问题 如何使另一个Controller(ASP.NET Web API CacheOutput库)的Web API缓存无效


我已经将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无效。


11803
2017-12-08 09:12


起源

我不确定,但[NoCache]属性可以帮助。 - Abhilab Das
我想要Cache,但只是想在员工控制器发生变化时无效 - Suresh


答案:


这有点棘手,但你可以用这种方式得到它:

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

10
2017-12-11 10:42



谢谢,但我使用ASP.Net 4.0和WebApi.OutputCache.V2只在ASP.net 4.5中可用吗?你有什么其他建议与ASP.Net 4.0一起工作吗?或者我必须将我的解决方案升级到asp.net 4.5 - Suresh
我不知道,我从未在ASP .NET 4.0中使用过WebApi.OutputCache。 - giacomelli
似乎你的解决方案适用于4.5,因为它没有解决我的问题,但接受答案希望,这将有助于其他人。 - Suresh
优秀!正是我需要的。 - David M