استفاده از ProtectedSessionStore در پروژه DntSite
نویسنده: مهرجویی
تاریخ: ۱۴۰۳/۰۹/۰۱ ۰۰:۲۹
آدرس: www.dntips.ir
sessionStorage ذخیره کنم و پس از هدایت کاربر به صفحه تایید شماره ذخیره شده را بازیابی کنم. دز زمان ذخیره مقدار در sessionStorage با متد SetAsync دچار خطای زیر می شود.JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
@page "/"
@{
httpContext.Session.SetString("name", "Test");
Name = httpContext.Session.GetString("name");
}
@Name
@code{
[CascadingParameter] HttpContext? httpContext{ get; set; }
private string Name = "";
}@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage ProtectedLocalStore
@if (isConnected)
{
<p>Current count: <strong>@currentCount</strong></p>
<button @onclick="IncrementCount">Increment</button>
}
else
{
<p>Loading...</p>
}
@code {
private int currentCount;
private bool isConnected;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
isConnected = true;
await LoadStateAsync();
StateHasChanged();
}
}
private async Task LoadStateAsync()
{
var result = await ProtectedLocalStore.GetAsync<int>("count");
currentCount = result.Success ? result.Value : 0;
}
private async Task IncrementCount()
{
currentCount++;
await ProtectedLocalStore.SetAsync("count", currentCount);
}
}