MVC global filter to load/maintain menus from database on page load

172 Views Asked by At

I am working on MVC5 applications where I have a base controller which is inherited by every controller in my application.

I am using OnActionExecuting function of base controller to load and maintain menus from database.

As this function will be called every-time any controller inherit base controller so some times it has been called more than once.

Can I use/create any other function from base controller which will be called once when view is about to render.

Is there any better way to maintain menus for the same user as in such case no need to hit database on every page, TIA.

1

There are 1 best solutions below

0
On

Good idea will be to use caching. For instance Cache Class where you can store objects and retrieve them by key.

public abstract class ControllerBase
{
    private readonly Cache _cache;

    public ControllerBase(Cache cache)
    {
        // null check
        _cache = cache;
    }

    protected virtual void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string username = filterContext.HttpContext.User.Identity.Name;

        // authenticate duser has always username
        if(!String.IsNullOrEmpty(username))
        {
            var cacheItem = _cache.Get("menu_" + username);

            if(cacheItem is {Type})
            {

            }
            else
            {
                // Load from db
                // Add to cache with sliding expiration
            }
        }
        else
        {
            var cacheItem = _cache.Get("menu_anonymous_user");

            if(cacheItem is {Type})
            {

            }
            else
            {
                // Load from db
                // Add to cache with sliding expiration
            }
        }
    }
}

It is an example. It can be done much better, but for an idea it is enough, I guess.