Blazor SessionStorage - Itens 返回转义字符

问题描述

在我的 Blazor 应用程序中,我正在会话存储中保存一些信息(它按预期工作,我可以在我的浏览器上看到它们并且它们格式正确):

await _sessionStorage.SetItemAsync("userCredentials",loginUser.UserCredentials);

enter image description here

但是当尝试从组件访问它们时:

@inject blazored.SessionStorage.ISessionStorageService sessionStorage;
...
@code{
...
    string myCrendentials = await sessionStorage.GetItemAsstringAsync("userCredentials");
...
}

结果将是 "\"111\""

enter image description here

解决方法

我首先会尝试使用一致的 API 调用

  • SetItemAsStringAsyncGetItemAsStringAsync

在您现在拥有的混合调用中 - 一个涉及 JSON 序列化,而另一个不涉及。

编辑:额外说明

当您调用 SetItemAsync 并向其传递一个字符串时,它会将字符串序列化为 JSON 并将 JSON 存储在会话存储中。 JSON 将包括引号:“测试”

如果您使用 GetItemAsStringAsync 检索此会话数据,它将以字符串形式返回您之前存储的 JSON:“Test”

当您调用 SetItemAsStringAsync 并将字符串传递给它时,它只是将字符串存储在会话存储中。此字符串将不包含引号:测试