且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-17 10:56:40

注意:此答案是从2018年12月开始的,当时有服务器端Blazor的早期版本可用.很有可能,它不再相关.

@JohnB暗示了穷人的国家态度:使用作用域服务.在服务器端Blazor中,作用域服务绑定到SignalR连接.这是最接近会话的内容.它对于单个用户当然是私有的.但是它也很容易丢失.重新加载页面或修改浏览器地址列表中的URL会加载以启动新的SignalR连接,创建新的服务实例,从而丢失状态.

The poor man's approach to state is a hinted by @JohnB: Use a scoped service. In server-side Blazor, scoped service as tied to the SignalR connection. This is the closest thing to a session you can get. It's certainly private to a single user. But it's also easily lost. Reloading the page or modifying the URL in the browser's address list loads start a new SignalR connection, creates a new service instance and thereby loses the state.

因此,首先创建状态服务:

So first create the state service:

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

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

Then configure the service in the Startup class of the App project (not server project):

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

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

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

Now you can inject the state into any Blazor page:

@inject SessionState state

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

更好的解决方案仍然是超级欢迎.

Better solutions are still super welcome.