简体   繁体   English

与 MySQL 的 ASP.NET Core 会话

[英]ASP.NET Core session with MySQL

I want to customize the session provider in asp.net core.我想在 asp.net 核心中自定义会话提供程序。 ie the custom session provider will use the MYSQL database instead of SQL Server I am seeing that asp.net core gives us the built-in method AddDistributedSqlServerCache.即自定义会话提供程序将使用MYSQL 数据库而不是SQL Server 我看到asp.net 核心为我们提供了内置方法AddDistributedSqlServerCache。 but it seems like this method is only for SQL server.但似乎这种方法仅适用于 SQL Server。

Can anyone help me regarding this?任何人都可以帮我解决这个问题吗?

Try this NuGet package instead.... 请尝试使用此NuGet软件包。

Pomelo.Extensions.Caching.MySql Pomelo.Extensions.Caching.MySql

Or this one for Postgresql.... 或用于Postgresql的...。

Community.Microsoft.Extensions.Caching.PostgreSQL Community.Microsoft.Extensions.Caching.PostgreSQL

I have below working implementation in .NET 5 or .NET 6 (also stands good for .NET Core)我在 .NET 5 或 .NET 6 中有以下工作实现(也适用于 .NET Core)

Add nuget package Pomelo.Extensions.Caching.MySql添加nuget包Pomelo.Extensions.Caching.MySql

At the top of ConfigureServices in Startup.cs在 Startup.cs 的 ConfigureServices 顶部

    services.AddDistributedMySqlCache(options =>
    {
        options.ConnectionString = <MySQL CnStr with: Allow User Variables=true; >;
        options.TableName = "WebUserSessions";
        options.SchemaName = <MySQL Database Name>;
    });
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(180);
        options.Cookie.IsEssential = true;
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
        options.Cookie.SameSite = SameSiteMode.Strict;
    });

In Configure method app.UseSession();在配置方法app.UseSession();

My SQL Table creation script:我的 SQL 表创建脚本:

CREATE TABLE `webusersessions` (
  `Id` varchar(449) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `AbsoluteExpiration` datetime(6) DEFAULT NULL,
  `ExpiresAtTime` datetime(6) NOT NULL,
  `SlidingExpirationInSeconds` bigint DEFAULT NULL,
  `Value` longblob NOT NULL,
  PRIMARY KEY (`Id`),
  KEY `Index_ExpiresAtTime` (`ExpiresAtTime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Now your session values are stored in MySQL Table 'WebUserSessions', thus you can serve your client from multiple servers using single mysql database for storing the sessions.现在您的会话值存储在 MySQL 表“WebUserSessions”中,因此您可以使用单个 mysql 数据库从多个服务器为您的客户端提供服务来存储会话。 In case you have only one server, your user's session would be preserved on IIS Application pool restart or Linux service restart.如果您只有一台服务器,您的用户会话将在 IIS 应用程序池重新启动或 Linux 服务重新启动时保留。

To update .NET core or .NET 6 application without any down time, please refer to my answer: https://stackoverflow.com/a/66580629/9659885要在不停机的情况下更新 .NET core 或 .NET 6 应用程序,请参考我的回答: https ://stackoverflow.com/a/66580629/9659885

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM