簡體   English   中英

Blazor ProtectedSessionStorage 不起作用

[英]Blazor ProtectedSessionStorage doesn't work

我嘗試在一些 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.

這是我的代碼:

會話服務.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);
        }
    }

啟動.cs

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

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

我錯了什么?


更新:

我忘記了 onInitialized 方法的異步,現在代碼不會停止,也不會從他的 scope 退出。 但不幸的是,我在瀏覽器控制台上收到此錯誤。

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)

解決了!

當您嘗試插入 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, ...)
   {
       ...
   }
}

因此,為了解決我的所有問題,我將async插入OnInitialized()並向User class 添加了一個空構造函數

如果您的項目在 .Net 6 blazor 中,則無需執行此類 .cs 文件和所有操作。

簡單地在命名空間下添加並在 _import.cshtml 文件中注入服務。

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

對於組件中的設置和獲取項目,請使用以下語法

套裝物品:
await ProtectedSessionStore.SetAsync("count", currentCount);

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

現在在瀏覽器中檢查您的數據會自動加密和解密。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM