c# – 如何在服务器端blazor中存储会话数据

在服务器端Blazor应用程序中,我想存储一些在页面导航之间保留的状态.我该怎么做?

常规的ASP.NET核心会话状态似乎不可用,因为Session and app sate in ASP.NET Core中的以下注释很可能适用:

Session isn’t supported in 07001
apps because a 07002 may
execute independent of an HTTP context. For example,this can occur
when a long polling request is held open by a hub beyond the lifetime
of the request’s HTTP context.

GitHub问题Add support to SignalR for Session提到您可以使用Context.Items.但我不知道如何使用它,即我不知道如何访问HubConnectionContext实例.

我对会话状态的选择是什么?

解决方法

@JohnB暗示了穷人对国家的态度:使用范围内的服务.在服务器端Blazor中,作用域服务与SignalR连接相关联.这是您可以获得的会话最接近的事情.它对于单个用户来说当然是私密的.但它也很容易丢失.重新加载页面或修改浏览器地址列表中的URL加载启动一个新的SignalR连接,创建一个新的服务实例,从而失去状态.

所以首先创建状态服务:

public class SessionState
{
    public string SomeProperty { get; set; }
    public int AnotherProperty { get; set; }
}

然后在App项目的Startup类(而不是服务器项目)中配置服务:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<SessionState>();
    }

    public void Configure(IBlazorApplicationBuilder app)
    {
        app.AddComponent<Main>("app");
    }
}

现在您可以将状态注入任何Blazor页面:

@inject SessionState state

 <p>@state.SomeProperty</p>
 <p>@state.AnotherProperty</p>

更好的解决方案仍然受到欢迎.

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...