Blazor Cache Reload

Ever since I’ve used Blazor I have found it will pop-up the error box with no apparent reason. I have found it to occur most commonly when either opening a sleeping tab or duplicating a tab etc. I believe it is due to the browser not actually having an open connection to the server and just rendering the UI from the cache. This occurs even in production.

This is very annoying for the end users and in a recent project I received complaints about the way this works. It can often mean when opening the site for the first time you get this error. This is commonly found when accessing a site from mobile browsers where they are trying to save as much data for the user.

I have searched for this error numerous times without any successful fix. I have just found what I think is the solution.
First off though I will just point out this comment from Steve Sanderson where he offers a solution to see the error – up until now even this wasn’t possible.

This led me to this GitHub issue #26174 – Blazor Server Side Error: The list of component records is not valid, happens when close and reopen Browser with Continue where you left off

Whether or not this is the particular error (the list of component records is not valid) I was always receiving I still do not know, but it seems like the solution.

If you add the following to the _Host.cshtml page (from this comment) it will hopefully resolve the issue:

@{
    Response.Headers["Cache-Control"] = "no-store";
}

In .NET 6 this should be in _Host.cshtml too unless you add this to the _Layout.cshtml:

@Inject Microsoft.AspNetCore.Http.IHttpContextAccessor _HttpContext

@{
    _HttpContext.HttpContext.Response.Headers["Cache-Control"] = "no-store";
}

The _Host.cshtml page uses the _Layout.cshtml as it’s layout. [The reason for this is to enable the HeadOutlet component change on component page change. Since Blazor as with MVC and Razor pages renders from the inside out, when it gets to the _Host.cshtml it renders the component first thereby setting the HeadOutlet to whatever was set in that component which can then be updated when we hit the _Layout.cshtml page. Were we to add everything to the _Host.cshtml file both the component and the HeadOutlet would be rendered at the same time and the head would not get updated.] I still haven’t figured out the reason why the _Host.cshtml file recognises the Response.Headers as coming from PageBase and the _Layout.cshtml file does not. They’re both .cshtml files so it must be something configured in .NET 6 that recognises the pages as so.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.