深入浅出Blazor webassembly之Local storage
普通 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
ILocalStorageService
:- SetItemAsync()
- SetItemAsStringAsync()
- GetItemAsync()
- GetItemAsStringAsync()
- RemoveItemAsync()
- ClearAsync()
- LengthAsync()
- KeyAsync()
- ContainKeyAsync()
-
synchronous via
ISyncLocalStorageService
(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 SetItemAsString[Async]
and GetItemAsString[Async]
methods which will save and return raw string values from local storage.
示例代码:
@page "/" @inject ILocalStorageService LocalStorageService @inject ISyncLocalStorageService SyncLocalStorageService <h1>Hello, world!</h1> Welcome to your new app. <br/> <p>jwt:@Jwt</p> <button class="btn btn-primary" @onclick="SaveJwt"> Save Jwt</button> <SurveyPrompt Title="How is Blazor working for you?" /> @code{ private String Jwt; protected override void OnInitialized() { base.OnInitialized(); ReadJwt(); } private void ReadJwt() { Jwt = SyncLocalStorageService.GetItem<String>("jwt"); } private void SaveJwt() { SyncLocalStorageService.SetItem<String>("jwt", "jwt123"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律