加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:54:38 所属栏目:百科 来源:网络整理
导读:在服务器端Blazor应用程序中,我想存储一些在页面导航之间保留的状态.我该怎么做? 常规的ASP.NET核心会话状态似乎不可用,因为Session and app sate in ASP.NET Core中的以下注释很可能适用: Session isn’t supported in 07001 apps because a 07002 may ex
在服务器端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>

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读