在ASP .NET Core/Razor Pages中保持会话活动的解决方法可以通过以下步骤实现:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddSession(); // 添加Session服务
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseSession(); // 启用Session
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
@using Microsoft.AspNetCore.Http
private readonly IHttpContextAccessor _httpContextAccessor;
public YourPageModel(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void YourMethod()
{
// 设置Session值
_httpContextAccessor.HttpContext.Session.SetString("YourKey", "YourValue");
// 获取Session值
string value = _httpContextAccessor.HttpContext.Session.GetString("YourKey");
}
这样就可以在ASP .NET Core/Razor Pages中保持会话活动了。记得在使用Session之前,要确保已经启动了Distributed Cache(分布式缓存)。