普通 MVC 網頁應用本地存儲會往往采用 cookie, 而 Blazor wasm 應用和其他 SPA 架構類似, 基本不使用 cookie, 通常使用的是 Local storage 或 session storage.
Local storage 和 session storage的持久化能力不同, session storage 在浏覽器的 tab 頁關閉後, 将會自動失效, 而 Local storage 即使是重新開機浏覽器程序後也會繼續有效, 直到使用者清除本地緩存.
對于Blazor wasm 應用需要本地存儲的往往是 jwt 或 userId, 是以Local storage 更合适一些. session storage 相對雞肋一些, 完全可以使用 app state container 全局類代替, 是以不是本文關注的重點.
Blazor wasm 使用Local storage的方法有:
通過JS互操作方式調用java script API完成,
使用 blazor 現成元件, 最流行的元件是 blazored 的 LocalStorage, 首頁 https://github.com/blazored/LocalStorage
=====================================
使用 blazored 的 LocalStorage
1. 安裝元件, 指令: dotnet add package Blazored.LocalStorage
2. Program.cs 中注冊 LocalStorage 服務
3. _Imports.razor 檔案中引用一下, 以友善頁面使用 @using Blazored.LocalStorage
4. 需要存儲或讀取local storage的檔案, 使用依賴注入的方式, 注入 ILocalStorageService 或 ISyncLocalStorageService 服務, 前者是異步版, 後者是同步版, 推薦使用異步版.
The APIs available are:
asynchronous via <code>ILocalStorageService</code>:
SetItemAsync()
SetItemAsStringAsync()
GetItemAsync()
GetItemAsStringAsync()
RemoveItemAsync()
ClearAsync()
LengthAsync()
KeyAsync()
ContainKeyAsync()
synchronous via <code>ISyncLocalStorageService</code> (Synchronous methods are only available in Blazor WebAssembly):
SetItem()
SetItemAsString()
GetItem()
GetItemAsString()
RemoveItem()
Clear()
Length()
Key()
ContainKey()
Note: Blazored.LocalStorage methods will handle the serialisation and de-serialisation of the data for you, the exceptions are the <code>SetItemAsString[Async]</code> and <code>GetItemAsString[Async]</code> methods which will save and return raw string values from local storage.
示例代碼: