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

 Eva---LiuJ 发布于 2022-12-07 13:10

我已经将ASP.NET Web API CacheOutput库用于我的web.net的asp.net项目并且它工作正常,但是我有一个POST方法的另一个控制器,我想从该控制器使我的缓存无效.

[AutoInvalidateCacheOutput]
public class EmployeeApiController : ApiController
{ 
    [CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 100)]
    public IEnumerable GetData()
    {
        //Code here
    }
}


public class EmployeesController : BaseController
{
    [HttpPost]
    public ActionResult CreateEmployee (EmployeeEntity empInfo)
    {
        //Code Here
    }
}

我希望在员工控制器中添加\ update时使Employees Cache无效.

1 个回答
  • 这有点棘手,但你可以用这种方式得到它:

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

    2022-12-11 03:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有