如何在filterAttribute中缓存项目

时间:2010-12-01 17:51:53

标签: c# asp.net-mvc caching filterattribute

我如何使用缓存来帮助这个属性呢?主要是不需要对container.GetService进行大量调用并获取用户。我可以将一些缓存放到位,将身份作为键和计划器缓存为值,然后查看它吗?

    public class AdminsAndProgramManagersOnlyAttribute : FilterAttribute, IAuthorizationFilter
{
    public AdminsAndProgramManagersOnlyAttribute()
    {
        Order = 1; //Must come AFTER AuthenticateAttribute
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var userRepository = GlobalApplication.container.GetService<IRepository<ProjectPlannerInfo>>();
        var identity = filterContext.HttpContext.User.Identity;
        var planner = userRepository.GetAll().WhereEmailIs(identity.Name);

        if (!planner.IsInRole("Db Admin") || planner.ProgramManager == 1)
        {
            filterContext.Result = new RedirectToRouteResult("error", new RouteValueDictionary(new { controller = "Error", action = "InsufficientPrivileges", reason = "Contract" }));
        }
    }
}

...洙

这样的事情?

 public void OnAuthorization(AuthorizationContext filterContext)
    {
        var identity = filterContext.HttpContext.User.Identity;

        if (filterContext.HttpContext.Cache[identity.Name] == null)
        {
            if (filterContext.HttpContext.Cache["repo"] == null)
            {
                filterContext.HttpContext.Cache.Add("repo", GlobalApplication.container.GetService<IRepository<ProjectPlannerInfo>>(), null, DateTime.Now.AddSeconds(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }

            var userRepository = filterContext.HttpContext.Cache["repo"] as IRepository<ProjectPlannerInfo>;

            filterContext.HttpContext.Cache.Add(identity.Name, userRepository.GetAll().WhereEmailIs(identity.Name), null, DateTime.Now.AddSeconds(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        var planner = filterContext.HttpContext.Cache[identity.Name] as ProjectPlannerInfo;

        if (!planner.IsInRole("Db Admin") || planner.ProgramManager == 1)
        {
            filterContext.Result = new RedirectToRouteResult("error", new RouteValueDictionary(new { controller = "Error", action = "InsufficientPrivileges", reason = "Contract" }));
        }
    }

1 个答案:

答案 0 :(得分:2)

您可以使用内置缓存:

filterContext.HttpContext.Cache