Home > Backend Development > C++ > How to Prevent Caching in ASP.NET MVC Actions?

How to Prevent Caching in ASP.NET MVC Actions?

DDD
Release: 2025-01-14 15:16:43
Original
275 people have browsed it

How to Prevent Caching in ASP.NET MVC Actions?

Suppressing Caching in ASP.NET MVC Actions with Attributes

Challenge:

In ASP.NET MVC applications, you often need to prevent specific actions from caching data to ensure you always retrieve the latest information.

Solution:

1. Disabling jQuery Caching:

To stop jQuery from caching AJAX responses, use the cache: false option in your AJAX settings:

<code class="language-javascript">$.ajax({
    cache: false,
    // ... rest of your AJAX configuration
});</code>
Copy after login

2. Implementing a Custom NoCache Attribute:

For more precise control, create a custom attribute to manage caching within your MVC actions:

<code class="language-csharp">[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // Configure HTTP headers to disable caching
        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);
    }
}</code>
Copy after login

3. Applying the NoCache Attribute:

Apply the attribute to the controller or individual actions requiring no caching:

<code class="language-csharp">[NoCache]
public class SomeController : Controller
{
    // Controller actions
}</code>
Copy after login

4. Global Caching Prevention:

For a site-wide approach, apply the NoCache attribute to your base controller class:

<code class="language-csharp">[NoCache]
public class ControllerBase : Controller, IControllerBase
{
    // Controller actions
}</code>
Copy after login

5. Browser Cache Refresh:

After implementing these changes, remember to perform a hard refresh (Ctrl F5) in your browser to clear any existing cached data and see the updated results.

The above is the detailed content of How to Prevent Caching in ASP.NET MVC Actions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template