如何在Blazor Server应用中清除ProtectedSessionStorage所有会话?
Blazor Server中批量清除ProtectedSessionStorage会话的方案
方案一:维护自定义键列表(推荐)
ProtectedSessionStorage本身没有原生批量删除接口,可通过提前维护业务会话键的清单,实现批量删除:
- 定义所有用到的会话键集合:
// 补全你实际使用的25个键 private readonly List<string> _sessionKeys = new List<string> { "Client", "UserInfo", "Permission", "Role", // ... 其他键 };
- 退出登录时遍历删除:
// Delete multiple sessions foreach (var key in _sessionKeys) { await ProtectedSessionStore.DeleteAsync(key); }
如果不想手动维护键列表,可封装自定义会话存储服务自动跟踪所有存入的键:
public class CustomSessionStorage { private readonly ProtectedSessionStorage _protectedStore; private readonly List<string> _trackedKeys = new List<string>(); private const string KeysListKey = "TrackedSessionKeys"; public CustomSessionStorage(ProtectedSessionStorage protectedStore) { _protectedStore = protectedStore; _ = LoadTrackedKeysAsync(); } private async Task LoadTrackedKeysAsync() { var result = await _protectedStore.GetAsync<List<string>>(KeysListKey); if (result.Success) { _trackedKeys.AddRange(result.Value); } } public async Task SetAsync<T>(string key, T value) { await _protectedStore.SetAsync(key, value); if (!_trackedKeys.Contains(key)) { _trackedKeys.Add(key); await _protectedStore.SetAsync(KeysListKey, _trackedKeys); } } public async Task<ProtectedBrowserStorageResult<T>> GetAsync<T>(string key) { return await _protectedStore.GetAsync<T>(key); } public async Task DeleteAllAsync() { foreach (var key in _trackedKeys) { await _protectedStore.DeleteAsync(key); } await _protectedStore.DeleteAsync(KeysListKey); _trackedKeys.Clear(); } }
在Program.cs中注册服务:
builder.Services.AddScoped<CustomSessionStorage>();
使用时注入CustomSessionStorage,退出登录时调用:
await _customSessionStorage.DeleteAllAsync();
方案二:直接清除整个sessionStorage(简单但有风险)
若应用独占sessionStorage,无其他依赖存储,可通过JS互操作直接清空:
- 注入
IJSRuntime:
[Inject] private IJSRuntime JS { get; set; }
- 退出时执行:
// Delete multiple sessions await JS.InvokeVoidAsync("sessionStorage.clear");
注意:此方法会清除所有sessionStorage内容,包括Blazor框架自身的存储数据,若有第三方脚本依赖sessionStorage会受影响,需谨慎使用。
内容的提问来源于stack exchange,提问作者P.Parikh
相关产品推荐
相关产品推荐

