Welcome to Part 2 of the Blazor Server in .NET 6! If you haven’t already, go check out Part 1 of this five-part educational series. In this post, I will be diving into Blazor Protected Browser Storage. Blazor Protected Storage allows you to save data in a hashed session storage of up to 10MB. Since Protected Browser Storage uses
ProtectedSessionStorage to scope to the current tab, you are able to avoid bugs and confusing behavior across multiple tabs. Anyone who has stored any information in local storage or cookies understands this pain!
This application uses the built-in JsInteropand, therefore, it doesn’t always play well if you are using
ServerPrerendered as your render mode for the application. There are a few ways to handle this problem that can be found here prerendering. In the meantime, let’s dive into adding some session storage to our CharacterBuilder application.
Typically there was would be some required installation, but luckily this package already comes with Blazor Server in .NET 6, so there is nothing more to install!
Creating a Base Component
In order to create a base component, we will add a class at the root of the Component folder called
BaseComponent, which inherits from
ComponentBase. This will be used by all our components to house shared logic available to all components.
Next, we will inject
ProtectedSessionStorage as a private property into the base component. Normally, I would create a wrapper around
ProtectedSessionStorage to house all my storage methods and inject that into the base component. However, this method will work just fine for the few we are making.
One common JsInterop issue when working with event base components is not disposing of the event properly. When the component is rerendered a new
Implementing ProtectedStorage on the Characters Page
Now that we have the
BaseComponent built, we need to change the
CharactersPageBase to inherit from that instead of the
In order to do this, we will add a method to either get the characters using the
BaseComponent method or get them from the mock service and set them using the set method in the
BaseComponent. This method will allow us to seed the
SessionStorage when the page is first loaded. It also requires changing the
OnInitializedAsync method to use your new seed method instead.
See Our Hashed Data
If you run the application and view the session storage in your developer tools, you will see our key of Characters and the hashed value! We did it!
In Part 2 of the Keyhole Blazor Server in .NET 6 series, we learned how to utilize Blazor Protected Browser Storage. We also covered how to build a base component and implement ProtectedStorage on the Characters Page.
Hopefully, you also found that using ProtectedSessionStorage to scope to the current tab allows you to avoid bugs and confusing behavior across multiple tabs. In the next blog, we will cover the installation of Radzen Blazor – a free component library for Blazor. See you in Part 3!