Images, CSS files, and JavaScript files in asp.net mvc are experiencing issues with caching

To ensure better security and consistency, I made sure that my pages were not cached. Whenever I pressed the back button on my browser, it always contacted the server to retrieve the HTML content.

I accomplished this by implementing a custom action filter as shown below:

public class NoCache : 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);
    }
}

I applied this global filter to all actions using the following code snippet:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    // Prevents any cached pages from being served to browsers, including Chrome
    filters.Add(new NoCache());
}

While this solution solved the initial problem, it also prevented Images, CSS, and JavaScript files from being cached. How can I instruct the application to cache them?

Answer №1

If you're looking to improve performance, consider enabling cache in your web.config:

The <clientCache> element within the <staticContent> element dictates the cache-related HTTP headers that IIS sends to Web clients. These headers help control how content is cached by Web clients and proxy servers.

An example of this is the httpExpires attribute, which sets an expiration date and time for the content. IIS then includes an HTTP "Expires" header with the response. The value for the httpExpires attribute needs to be a fully-formatted date and time following the RFC 1123 specification. For instance:

<configuration>
   <system.webServer>
      <staticContent>
         <clientCache cacheControlMode="UseExpires"
            httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
      </staticContent>
   </system.webServer>
</configuration>

For more information, check out this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js allows for client-side JavaScript execution on BrowserStack

After developing a tool to automate visual regression within an E2E test suite, I have encountered a challenge when trying to measure visual regression with autoplaying HTML5 videos. Due to the dynamic nature of videos and the variability in Browserstack&a ...

Utilizing underscore.js to aggregate data points: A comprehensive guide

If I have an array containing 6 numeric data points and I want to transform it into a new array with only 3 data points, where each point is the sum of two of the original points. For example: [1,1,1,1,1,1] would become [2,2,2] What would be the most eff ...

Is it possible to link Discourse with ASP.NET user registration databases?

Has anyone successfully integrated the Discourse forum software () with asp.net membership tables? Are there any examples or tutorials available for this integration? ...

What is the importance of including parentheses when passing a function to a directive?

Hello, I'm currently a beginner in Angular and I am experimenting with directives. Here is the code snippet that I am using: HTML <div ng-app="scopetest" ng-controller="controller"> <div phone action="callhome()"> </div> </div ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

When passing a parameter in a JSP page, it returns a null value

How can I display the name of my image like so? This is a simple post request from demo.jsp to itself. <form method="post" action="demo.jsp"> <input type="hidden" id="sql" name="name" value="sql"/> <input type="image" src="images/icons/ic ...

The PHP script fails to execute within HTML elements

Hey there! I'm currently working on designing my own error page, which involves extracting some data from the URL. At the top of my error.php file, here is the code I have: <?php $error_message = $_GET["error_message"]; if(!$error_message) { ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

Tips on retrieving the value of every cell within a row and then transferring it to a corresponding text box within the same row

What is the process for extracting the value of each cell in a row and setting it as the value of the corresponding text box in that row? <tr> <td class="oridinal-number">1</td> <td class="number"> 123456 ...

Redirect to the last folder with an ASP.NET 301 redirection

I have a task to create a 301 redirect for all previous links that include (/CID-VALUE), such as www.example.com/folder1/folder2/CID-1234. These links may have been located in any folder, so I need a solution that captures all occurrences of CID- along wit ...

Working with loops and databases in ASP.NET using VB without referencing the Datatable object

I've encountered a problem with my code that involves looping through a data table and inserting the data into a database. The issue is that the data is inserted correctly during the first loop, but then duplicates itself for the remaining loops. As a ...

Enabling or Disabling Inputs in Angular

I'm looking to customize my form behavior in a specific way - when I click on the modify button, I want only one line to be modified instead of all three. How can I achieve this? Images : edit save app.component.html : <table mat-table [dataSourc ...

Disabling the camera feed in a React application

Attempting to turn off the webcam using javaScript in React has been a bit challenging. Whenever I shift to a new component or when a component is destroyed, my react component immediately moves to the next page, but the webcam light remains on in the new ...

I want to know how to use PHP to count the number of occurrences of a specific value in a MySQL table and then echo the count. Can you help me with

I am working with a MySQL table that contains several varchars in one column. My goal is to determine the number of times a specific varchar appears in this column and then display that count using PHP. Can anyone provide me with the necessary SQL code to ...

Understanding the request URL in Ajax when receiving a response

How can the URL of a jQuery request be retrieved from the response received? Perhaps something like this: function retrieveUrlFromResponse(response, url){ requestUrl = url; } ...

HtmlButton failing to execute client-side validation on IE11

I am encountering a strange problem with a web form using the HTMLButton in an asp.net environment. Due to formatting requirements, I need to utilize a <button> construct which functions properly in all browsers except for IE11. <button id="cmdLo ...

I must utilize the row variable obtained from my controller in order to transmit it to another controller using Ajax

When displaying a menu of categories and products for an authenticated user, I encountered a problem with the search bar. Despite wanting only certain categories/products to be displayed, the search bar was fetching products from all categories. To address ...

It appears that Internet Explorer is still animating/processing my loading.gif despite being set to display:none

It seems that the issue I'm encountering is related to the inconsistent starting position of the loading.gif animation when performing an ajax request. In Internet Explorer, the animation appears to start from a random point, while in Firefox it alway ...

After a period of running NodeJS and AngularJS together, I am encountering the net::ERR_CONNECTION_RESET error

My setup includes Express with NodeJS and AngularJS on the front-end. However, after performing a series of actions such as adding data, updating records, and showing a list, I encounter the error net::ERR_CONNECTION_RESET. Interestingly, this error only o ...

Why are the items I have inserted inside my <div> tag not appearing on the screen?

What could be simpler than this: {this.state.dash ? <div className='dashWrapper slide'> HELLO </div> : null} I've tried everything, but nothing seems to show up inside the div. ...