"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to prevent caching of ASP.NET MVC actions?

How to prevent caching of ASP.NET MVC actions?

Posted on 2025-04-11
Browse:332

How Do I Prevent Caching for Specific ASP.NET MVC Actions?

Controlling Caching in ASP.NET MVC Actions

ASP.NET MVC's caching mechanism significantly boosts performance. However, scenarios exist where disabling caching for particular actions is vital to guarantee the retrieval of fresh data. This guide details methods to prevent caching in specific ASP.NET MVC actions using custom attributes.

Creating a NoCache Attribute

To build a custom attribute that disables caching, we leverage the [AttributeUsage] and [ActionFilterAttribute] attributes. Below is an example:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Applying [NoCache] to a controller or action method disables caching for that specific element. Alternatively, inheriting from a base controller and decorating it with [NoCache] prevents caching across all inheriting controllers.

jQuery's Cache Control

When using jQuery for data retrieval, explicitly setting cache: false within the $.ajax() method prevents caching:

$.ajax({
    cache: false,
    // ... other AJAX settings
});

Enforcing Browser Refresh

After implementing anti-caching measures, a "hard refresh" (Ctrl F5) is crucial to ensure the browser doesn't rely on cached data. A standard refresh (F5) might not always retrieve the latest information if the browser retains the cached version.

Summary

Utilizing the NoCacheAttribute or setting cache: false in jQuery effectively prevents caching for targeted ASP.NET MVC actions, guaranteeing the browser receives current data. Mastering caching control is key to avoiding stale data impacting user experience and application logic.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3