使用无交互性的 Blazor SSR。 我需要在每个页面的初始化期间读取会话存储。 我尝试过 Nuget 'Blazored.SessionStorage',但这需要交互性。 我也尝试过 HttpContext.Session.GetString,但无法使其工作。 有什么建议么?谢谢。
//--- Test HttpContext - Fail
private async Task Test1()
{
HttpContext.Session.GetString("testKey");
}
//--- Test NuGet Blazored.SessionStorage - Fail
private async Task Test2()
{
await sessionStorage.SetItemAsync("name", "John Smith");
var name = await sessionStorage.GetItemAsync<string>("name");
}
当您使用SSR时,访问SessionStorage将与Asp.net Core MVC中相同。您可以在
@{...}
大括号中编写执行代码。在 SSR 页面中尝试以下操作:...
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
...
app.UseSession();
索引.剃刀
@page "/"
@{
httpContext.Session.SetString("name", "John Smith");
Name = httpContext.Session.GetString("name");
}
@Name
@code{
[CascadingParameter]HttpContext? httpContext{ get; set; }
private string Name = "";
}
测试结果
参考:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0#ihttpcontextaccessorhttpcontext-in-razor-components-blazor