session - NET Core 服务器端多 session Blazor

标签 session asp.net-core blazor

我正在尝试在我的服务器上托管我的 Blazor 应用程序。
我整个夏天都花在它上面,我只是意识到每次我在新设备上打开我的网站时,它不会创建一个从零开始的新 session ,而是继续我离开它的地方。最糟糕的是它背后有一个登录系统,所以我现在觉得 super 愚蠢。

我真的需要一个关于如何解决这个“不小的”问题的重要提示。
有没有办法让服务器在每次有人打开网站时创建新 session (而不会让其他用户松散)?

解决方案应该改用客户端模板,但性能确实很慢。

更新:
帐户“用户密码”是:
- 用户用户
- 测试一下

Download project sample (requires Net Core 3.0)

[解决方案] itminus 找到了我的问题的解决方案。

您还必须添加 ConfigureServices在 Startup.cs 这个 services.AddScoped<Storage>();

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<Storage>();
        }

最佳答案

every time I open my website on new device it doesn't create a new session restarting from zero, but continues where I left it.



我检查了您的代码,发现您正在使用单例模式来初始化 Storage .如果我理解正确,这个 Storage单例实例将在不同用户之间共享(也跨不同设备)。因为这个实例将用于渲染 Main.razor页面,您现在会遇到并发问题。

为了解决这个问题,存储实例应该被限制在某个特定的连接中。当您使用 Blazor 服务器端时,您可以将存储注册为 Scoped Service :

In Blazor Server apps, a scoped service registration is scoped to the connection. For this reason, using scoped services is preferred for services that should be scoped to the current user, even if the current intent is to run client-side in the browser.



首先,删除静态单例实例:
public class Storage
{
    private static Storage instance;
    private Storage()                         
    {                                         
    }                                         
    public static Storage GetInstance()       
    {                                         
         if (Storage.instance == null)        
             Storage.instance = new Storage();
         return Storage.instance;             
     }                                        

    public List<Items>list {get;set;} = new List<Items>();
    public string password {get;set;}

}

Register this Class as a scoped service:

services.AddScoped<Storage>();

然后将此服务注入(inject)您的Login.razorMain.razor :
@inject project.Storage Storage

最后,您需要更改所有 Storage.GetInstance().Storage. :

    Storage.list = Order;
    ...
    Storage.password = password;

我注意到您也在创建 Importer/Additional使用单例模式的实例。我建议您应该重构它们以以类似的方式使用服务注入(inject)。

关于session - NET Core 服务器端多 session Blazor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57856598/

相关文章:

php - session_start 挂起

asp.net - 错误 "dotnet : Could not find any project in ` C :\** ."when running "dotnet add package Microsoft. AspNetCore.Authentication.MicrosoftAccount”

c# - 使用 Blazor Server 检查表单提交后如何重定向到另一个页面?

laravel - 机器人没有 Laravel session

java - 如何向 Postgresql CopyManager 指示 session 实例

model-view-controller - 使用 Grails 时,我应该关心 Open Session in View 吗?

asp.net-web-api - 用于 WebAPI 的 MVC favicon.ico 路由

c# - 从 .NET Framework 传统项目中引用 .NET Standard csproj 项目

c# - 重新保存Blazor WASM的.razor文件

c# - 如何从 blazor 应用程序调用 Azure AD B2C 编辑配置文件用户流程?