首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ProtectedSessionStorage不起作用

ProtectedSessionStorage不起作用
EN

Stack Overflow用户
提问于 2022-02-09 13:33:51
回答 2查看 2.4K关注 0票数 0

我尝试在一些Blazor组件中实现ProtectedSessionStorage (.NetCore 6,Blazor )。

我也遵循了这个线程:Blazor ProtectedSessionStorage object NULL,但是当我试图设置会话数据时,代码会停止并立即退出他的作用域。

这是我的密码:

SessionService.cs

代码语言:javascript
运行
复制
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
...

    public class SessionService
    {
        private ProtectedSessionStorage _sessionStorage;

        public SessionService(ProtectedSessionStorage storage)
        {
            _sessionStorage = storage;
        }

        public async Task<User> GetUserProperty()
        {
            var value = await _sessionStorage.GetAsync<User>("user");
            return value.Value;
        }

        public async Task SetUserProperty(User value)
        {
            await _sessionStorage.SetAsync("user", value);
        }
    }

Startup.cs

代码语言:javascript
运行
复制
public void ConfigureServices(IServiceCollection services)
{
    ...
    //registering the service
    services.addScoped<SessionService>();
    ...
}

MyComponent.razor

代码语言:javascript
运行
复制
@code
{
   [Inject] public SessionService SessionService { get; set; } = default!;

   protected override async void OnInitialized()
   {
       InitUser();
       LoadInterface();
   }

   protected async Task InitUser()
   {
      ...
      try
      {
          User user = new User("id", "location"); 
          //after this row, code exit from this scope
          await SessionService.SetUserProperty(user);

          //this part of code aren't read
          if(..)
          {
             //some other check
          }
          ...
      }
      catch(Exception ex)
      {
          //No exceptions caught
      }
      
   }
{

我做错什么了?

更新:

我忘记了onInitialized方法上的异步,现在代码不停止,也不退出他的作用域。但不幸的是,我在浏览器控制台上收到了这个错误。

代码语言:javascript
运行
复制
blazor.server.js:1 
        
       [2022-02-09T17:11:25.128Z] Error: System.InvalidOperationException: Each parameter in the deserialization constructor on type 'MyProject.Models.Shared.User' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.Unprotect[TValue](String purpose, String protectedJson)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.GetAsync[TValue](String purpose, String key)
   at MyProject.Services.Dashboard.SessionService.GetUserProperty() in C:\Source\MyProject\Services\Dashboard\SessionService.cs:line 18
   at MyProject.Shared.DashHeaderMenu.OnInitialized() in C:\Source\MyProject\Shared\DashHeaderMenu.razor:line 128
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__127_0(Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteSynchronously(TaskCompletionSource`1 completion, SendOrPostCallback d, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c.<.cctor>b__23_0(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteBackground(WorkItem item)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-02-10 09:29:02

解决了!

当您尝试插入对象时,如自定义类(在我的示例中是User),您需要添加一个用于序列化的空构造函数,并将其放入受保护的会话存储中。

代码语言:javascript
运行
复制
public class User
{
   public string name;
   public string surname;
   public int id;
   .....

   //required for serialization
   public User(){}

   //others constructor used
   public User(string name, string surname, ...)
   {
       ...
   }
}

因此,为了解决所有问题,我将async插入到OnInitialized()中,并向User类添加一个空构造函数。

票数 2
EN

Stack Overflow用户

发布于 2022-09-12 14:40:58

如果您的项目在.Net 6 blazor中,那么就不需要做这些类型的.cs文件等等。

简单地在命名空间下面添加并在_import.cshtml文件中注入服务。

@inject ProtectedSessionStorage ProtectedSessionStore

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage

对于组件中的set和get项,请使用下面的语法

集项目:

await ProtectedSessionStore.SetAsync("count", currentCount);

Get项目:

var result = await ProtectedSessionStore.GetAsync<int>("count");

currentCount = result.Success ? result.Value : 0;

现在签入浏览器,您的数据将自动加密和解密。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71050516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档