Monday, February 6, 2017

Asp.Net MVC Outputcache in base controller not working

Leave a Comment

I am using output cache attribute in asp.net mvc base controller but it is being called every time as it is in OnActionExecuting. Is there any option to call the method only onetime to load all default values?

    protected override void OnActionExecuting(ActionExecutingContext filterContext)     {         GetDefaults();         base.OnActionExecuting(filterContext);     }      [OutputCache(Duration = 60000)]     private ActionResult GetDefaults()     {      //code to load all my default values      // Viewdata values used in all pages in my aplication      // Viewdata values used in all pages in my aplication      // Viewdata values used in all pages in my aplication      return null;     } 

Any other best practice to load all default values for all pages and cache them?

2 Answers

Answers 1

You can use either Application_Start() or Session_Start() in the Global.asax.cs for storing data only once depending on whether you want the data to be refreshed on application start or per session start. That would be up to what your application needs to do.

Having a base controller like you did is good if you need something to be done for every action. The most common being the [Authorize] filter that you need to do for every action to see if the user is authorized for security reasons. Another way to do this is also writing your own ActionFilterAttribute and doing the caching part you need to do. Then all you need to do is to add this new Action filter to any of the actions that you need to do this caching. Pleas see here for how to do this : https://msdn.microsoft.com/en-us/library/dd410056(v=vs.98).aspx But since you want the data to load only once I think an action filter may NOT be the right place to do caching.

Answers 2

There is no way to leverage the the cache engine here. The reason is obvious if you consider why it (caching) actually works, when an action is called it is never the user code that's calling it, it is always the mvc framework that does. That way it has a chance to apply caching. In your example the user code is calling the method directly, there is no indirection here, just a plain old call - no caching is involved.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment