I try to implement ProtectedSessionStorage in some Blazor components (.NetCore 6, Blazor Server).
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
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
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
}
}
{
What I Wrong?
Update:
I forgot async on onInitialized method and now code don't stop and don't exit from his 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)
CodePudding user response:
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.
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