如何在服务器端blazor中存储会话数据 [英] How to store session data in server-side blazor
问题描述
在服务器端Blazor应用程序中,我想存储页面导航之间保留的某些状态.我该怎么办?
In a server-side Blazor app I'd like to store some state that is retained between page navigation. How can I do it?
Regular ASP.NET Core session state does not seem to be available as most likely the following note in Session and app sate in ASP.NET Core applies:
SignalR 不支持会话应用程序,因为 SignalR Hub 可能独立于HTTP上下文执行.例如,这可能发生当集线器在其生存期内超过了长时间的轮询请求时请求的HTTP上下文.
Session isn't supported in SignalR apps because a SignalR Hub 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问题添加对Session的SignalR支持提到您可以使用 HubConnectionContext
实例.
The GitHub issue Add support to SignalR for Session mentions that you can use Context.Items. But I have no idea how to use it, i.e. I don't know hot to access the HubConnectionContext
instance.
我对会话状态有哪些选择?
What are my options for session state?
推荐答案
注意:此答案是从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.
这篇关于如何在服务器端blazor中存储会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!