<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/net-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 18 Feb 2021 04:35:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Caching Static Resources Forever with ASP.NET Core</title>
		<link>https://topreviewhostingasp.net/caching-static-resources-forever-with-asp-net-core/</link>
					<comments>https://topreviewhostingasp.net/caching-static-resources-forever-with-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 18 Feb 2021 04:11:12 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp.net core]]></category>
		<category><![CDATA[asp.net core tips]]></category>
		<category><![CDATA[asp.net core tutorial]]></category>
		<category><![CDATA[caching asp net core]]></category>
		<category><![CDATA[net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2924</guid>

					<description><![CDATA[Caching static resources like stylesheet, JavaScript, or image files allows improving the performance of your website. On the client-side, a static file will always be loaded from the cache which reduces the number of requests to the server and so, the time to get the page and its resources. On the server-side, as they are [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Caching static resources like stylesheet, JavaScript, or image files allows improving the performance of your website. On the client-side, a static file will always be loaded from the cache which reduces the number of requests to the server and so, the time to get the page and its resources. On the server-side, as they are fewer requests, the server can handle more clients without upgrading the hardware.</p>



<p>While caching is a great thing, you must ensure the client is always running the latest version of the application. I mean, when you deploy the next version of the website, you don&#8217;t want the client to use an obsolete cached version of a file.</p>



<h2 class="wp-block-heading">Versioned URL (Cache buster)</h2>



<p>To ensure the user always uses the latest version of a file, we must have a unique URL per version of a file. There are many strategies:</p>



<ul>
<li>Use the query string: <code>https://sample.com/file.js?v=123</code></li>
<li>Rename the file: <code>https://sample.com/file.123.js</code></li>
<li>Create a directory: <code>https://sample.com/123/file.js</code></li>
</ul>



<p>ASP.NET Core provides a mechanism using a <code>TagHelper</code> to append the version with the query string. It supports the most common HTML tags that target a static resource: <code>script</code>, <code>link</code> and <code>img</code>. All you have to do is append <code>asp-append-version="true"</code> to the tag:</p>



<pre class="wp-block-code"><code>&lt;link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /&gt;
&lt;script src="~/js/site.js" asp-append-version="true"&gt;&lt;/script&gt;
&lt;img src="~/images/banner1.svg" asp-append-version="true" /&gt;</code></pre>



<p>This will produce:</p>



<pre class="wp-block-code"><code>&lt;link rel="stylesheet" href="/css/site.css?v=1wp5zz4e-mOPFx4X2O8seW_DmUtePn5xFJk1vB7JKRc" /&gt;
&lt;script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"&gt;&lt;/script&gt;
&lt;img src="/images/banner1.svg?v=GaE_EmkeBf-yBbrJ26lpkGd4jkOSh1eVKJaNOw9I4uk" /&gt;</code></pre>



<p>The version is the SHA256 of the file encoded in base64. Of course, the hash is computed only once per file and stored in an <code>IMemoryCache</code>.</p>



<p>The URL of files are now unique and will change when the file change, so we can add a cache header to the response to indicate the client that the file can be stored in cache forever.</p>



<h2 class="wp-block-heading">Response headers</h2>



<p>To indicate the browser to store the file in its cache, we must send the <code>Cache-control</code> header and the <code>Expires</code> header for <code>HTTP/1.0</code> compatibility. To add these headers, we use the <code>OnPrepareResponse</code> callback of the <code>StaticFilesOptions</code>. Let&#8217;s modify the <code>Startup.cs</code> file:</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = context =&gt;
        {
            // Cache static file for 1 year
            if (!string.IsNullOrEmpty(context.Context.Request.Query["v"]))
            {
                context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" });
                context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
            }
        }
    });

    app.UseMvc(routes =&gt;
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}</code></pre>



<p>You can check the headers are sent by using the Developer Console:</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="773" height="275" class="wp-image-2925" src="https://topreviewhostingasp.net/wp-content/uploads/2021/02/developerconsole.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/02/developerconsole.png 773w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/developerconsole-300x107.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/developerconsole-768x273.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2021/02/developerconsole-50x18.png 50w" sizes="(max-width: 773px) 100vw, 773px" /></figure>



<h2 class="wp-block-heading" id="conclusion-60e67e">Conclusion</h2>



<p>Using HTTP caching is important for performance reasons (client and server sides). With ASP.NET Core, you can take advantage of the provided <code>TagHelper</code>s to generate a versioned URL, and change the default configuration of the <code>StaticFilesMiddleware</code> to add the <code>Cache-control</code> header for these URLs.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/caching-static-resources-forever-with-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
