You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中Blazor应用替代已弃用ProtectedBrowserStorage的方案

.NET 8 中替代弃用的 ProtectedBrowserStorage 的方案

在.NET 8里,原来Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage命名空间下的类型已经被迁移到**Microsoft.AspNetCore.Components.Web.ProtectedBrowserStorage**,功能完全一致,只是命名空间做了统一调整,不需要额外找其他替代库。

具体修改步骤:

  • 替换引用的命名空间:把原来的@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage改成@using Microsoft.AspNetCore.Components.Web.ProtectedBrowserStorage
  • 注入代码无需修改,依然使用ProtectedSessionStorage类型,注入名称可以保持原来的ProtectedSessionStore

完整代码示例:

@using Microsoft.AspNetCore.Components.Web.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore

<button @onclick="SaveSessionData">保存数据到SessionStorage</button>
<button @onclick="LoadSessionData">加载SessionStorage数据</button>
<p>加载结果:@displayValue</p>

@code {
    private string displayValue;

    private async Task SaveSessionData()
    {
        // 加密存储数据到SessionStorage
        await ProtectedSessionStore.SetAsync("user_preference", "dark_mode");
    }

    private async Task LoadSessionData()
    {
        var dataResult = await ProtectedSessionStore.GetAsync<string>("user_preference");
        displayValue = dataResult.Success ? dataResult.Value : "未找到对应数据";
    }
}

补充说明:

  • 这个新命名空间下的ProtectedSessionStorage和旧版逻辑完全一样,依然会对存储的数据进行加密,避免敏感信息明文暴露在浏览器存储中。
  • 如果需要操作LocalStorage,同样可以使用同命名空间下的ProtectedLocalStorage,用法和上述示例一致。

内容的提问来源于stack exchange,提问作者Gary Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:07:31