Content Output Caching – Part 3

It is possible to easily cache the rendering of a web page using a custom condition by setting a custom string, which ASP.NET will vary the output by. To test it, you need to create a class that inherits from MvcOutputCacheAttribute. Take a look at the following example:

public class VaryByBrowser : Verndale.OutputCache.Attributes.MvcOutputCacheAttribute
	protected override string GetVaryByCustomString(ControllerContext filterContext)
		if (PageEditing.PageIsInEditMode)
			return null;

		return filterContext.HttpContext.Request.Browser.Browser;

In this case, our caching will be varied based on which browser the user accesses the page with. The action method in the controller should be decorated like this:

public class MyController : PageController<Page>
	public ActionResult Index(Page currentPage)
		var model = PageViewModel.Create(currentPage);
		return View(model);

Try accessing the page from different browsers. You will see that the output now depends on which browser you use.

It is perhaps not the solution to all your problems but it shows a nice utility of Output Caching.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s