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

Blazor Server(.NET7)中ProtectedLocalStorage获取数据为空的解决方法

问题原因与修复方案

核心问题

你的代码未正确处理异步操作:ProtectedLocalStorage的所有方法(SetAsync/GetAsync/DeleteAsync)都是异步方法,返回Task或Task<ProtectedBrowserStorageResult<T>>,但你直接调用这些方法却不等待执行完成,导致存储操作还没完成就去读取,读取时还错误地把Task对象转成字符串,自然拿不到真实的username值。

修复后的代码

修改login.razor中的方法,正确使用async/await并获取真实存储值:

@page "/login"
@inject ProtectedLocalStorage storage

<button @onclick="@StoreValueAsync">set session data</button>
<button @onclick="@RemoveValueAsync">remove session data</button>
<button @onclick="@GetValueAsync">get values</button>

@testString

@code {
    private string? testString = "teststring";

    public async Task StoreValueAsync()
    {
        await storage.SetAsync("username", "user");
        await storage.SetAsync("password", "pass");
    }

    public async Task RemoveValueAsync()
    {
        await storage.DeleteAsync("username");
        await storage.DeleteAsync("password");
    }

    public async Task GetValueAsync()
    {
        var userResult = await storage.GetAsync<string>("username");
        string? user = userResult.Value;

        var passResult = await storage.GetAsync<string>("password");
        string? pass = passResult.Value;

        testString = user != null 
            ? $"{user} and user is not null" 
            : $"user is null";
    }
}

关键修改点说明

  1. 异步方法签名:将所有按钮点击方法从void改为async Task,Blazor支持异步事件处理方法,必须这样才能使用await。
  2. 等待异步操作:调用storage的所有方法前加await,确保存储/读取操作完成后再执行后续代码。
  3. 正确获取存储值:GetAsync<T>返回ProtectedBrowserStorageResult<T>对象,需通过.Value属性获取实际存储的数据,而非直接对Task调用ToString()。
  4. 移除冗余HTML标签:Blazor页面不需要完整的html/head/body结构,这些会由项目布局文件(如_Layout.cshtml)统一提供,保留会导致DOM结构异常。

验证效果

点击「set session data」按钮后,再点击「get values」,就能正确显示user and user is not null,控制台也不会出现异常。


内容的提问来源于Stack Exchange,提问作者xxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:48:26