简体   繁体   English

Blazor ProtectedSessionStorage 不起作用

[英]Blazor ProtectedSessionStorage doesn't work

I try to implement ProtectedSessionStorage in some Blazor components (.NetCore 6, Blazor Server).我尝试在一些 Blazor 组件(.NetCore 6、Blazor 服务器)中实现 ProtectedSessionStorage。

I followed too this thread: Blazor ProtectedSessionStorage object NULL , but when I try to set session data the code stop and immediately exit from his scope. I followed too this thread: Blazor ProtectedSessionStorage object NULL , but when I try to set session data the code stop and immediately exit from his scope.

This is my code:这是我的代码:

SessionService.cs会话服务.cs

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启动.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    //registering the service
    services.addScoped<SessionService>();
    ...
}

MyComponent.razor MyComponent.razor

@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
      }
      
   }
{

What I Wrong?我错了什么?


Update:更新:

I forgot async on onInitialized method and now code don't stop and don't exit from his scope.我忘记了 onInitialized 方法的异步,现在代码不会停止,也不会从他的 scope 退出。 But unfortunately I receive this error on browser console.但不幸的是,我在浏览器控制台上收到此错误。

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)

Solved!解决了!

When you try to insert an object, like a custom class (in my case is User), you need add an empty constructor for serialize and put into the Protected Session Storage.当您尝试插入 object 时,例如自定义 class(在我的情况下是用户),您需要添加一个空构造函数进行序列化并放入受保护的 Session 存储。

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, ...)
   {
       ...
   }
}

So, for solve all my problems I inserted async to OnInitialized() and add a empty constructor to User class因此,为了解决我的所有问题,我将async插入OnInitialized()并向User class 添加了一个空构造函数

If your project in.Net 6 blazor then no need to do these kind of.cs file and all.如果您的项目在 .Net 6 blazor 中,则无需执行此类 .cs 文件和所有操作。

simple add below namespace and inject service in _import.cshtml file.简单地在命名空间下添加并在 _import.cshtml 文件中注入服务。

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

and for set and get items in component use below syntax对于组件中的设置和获取项目,请使用以下语法

Set Item:套装物品:
await ProtectedSessionStore.SetAsync("count", currentCount);

Get Item:获取物品:
var result = await ProtectedSessionStore.GetAsync<int>("count");
currentCount = result.Success? result.Value: 0;

and now check in browser your data is automatically encrypted and decrypted.现在在浏览器中检查您的数据会自动加密和解密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM