我尝试在一些Blazor组件中实现ProtectedSessionStorage (.NetCore 6,Blazor )。
我也遵循了这个线程:Blazor ProtectedSessionStorage object NULL,但是当我试图设置会话数据时,代码会停止并立即退出他的作用域。
这是我的密码:
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
}
}
{
我做错什么了?
更新:
我忘记了onInitialized方法上的异步,现在代码不停止,也不退出他的作用域。但不幸的是,我在浏览器控制台上收到了这个错误。
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)
发布于 2022-02-10 09:29:02
解决了!
当您尝试插入对象时,如自定义类(在我的示例中是User),您需要添加一个用于序列化的空构造函数,并将其放入受保护的会话存储中。
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
类添加一个空构造函数。
发布于 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;
现在签入浏览器,您的数据将自动加密和解密。
https://stackoverflow.com/questions/71050516
复制相似问题