远程应用会话状态

远程应用会话状态将启用 ASP.NET Core 与 ASP.NET 应用之间的通信以检索会话状态。 这是通过公开 ASP.NET 应用上的终结点来实现的,该终结点可以查询以检索和设置会话状态。

HttpSessionState 序列化

必须序列化 HttpSessionState 对象才能启用远程应用会话状态。 这是通过实现 Microsoft.AspNetCore.SystemWebAdapters.SessionState.Serialization.ISessionSerializer 类型来实现的,其中提供了默认的二进制编写器实现。 这是由以下代码添加的:

builder.Services.AddSystemWebAdapters()
    .AddSessionSerializer(options =>
    {
        // Customize session serialization here
    });

配置

首先,按照远程应用设置说明连接 ASP.NET Core 和 ASP.NET 应用。 然后,只需调用几个额外的扩展方法即可启用远程应用会话状态。

ASP.NET Core的配置涉及调用 AddRemoteAppSessionAddJsonSessionSerializer 注册已知的会话项类型。 该代码应该类似于以下内容:

builder.Services.AddSystemWebAdapters()
    .AddJsonSessionSerializer(options =>
    {
        // Serialization/deserialization requires each session key to be registered to a type
        options.RegisterKey<int>("test-value");
        options.RegisterKey<SessionDemoModel>("SampleSessionItem");
    })
    .AddRemoteAppClient(options =>
    {
        // Provide the URL for the remote app that has enabled session querying
        options.RemoteAppUrl = new(builder.Configuration["ReverseProxy:Clusters:fallbackCluster:Destinations:fallbackApp:Address"]);

        // Provide a strong API key that will be used to authenticate the request on the remote app for querying the session
        options.ApiKey = builder.Configuration["RemoteAppApiKey"];
    })
    .AddSessionClient();

会话支持需要对 ASP.NET Core 管道执行额外的工作,默认情况下不会启用。 可以通过 ASP.NET Core 元数据按路由配置它。

例如,会话支持要求为控制器添加批注:

[Session]
public class SomeController : Controller
{
}

或默认为所有终结点启用:

app.MapDefaultControllerRoute()
    .RequireSystemWebAdapterSession();

框架等效项类似于 Global.asax.cs 中的以下更改:

SystemWebAdapterConfiguration.AddSystemWebAdapters(this)
    .AddJsonSessionSerializer(options =>
    {
        // Serialization/deserialization requires each session key to be registered to a type
        options.RegisterKey<int>("test-value");
        options.RegisterKey<SessionDemoModel>("SampleSessionItem");
    })
    // Provide a strong API key that will be used to authenticate the request on the remote app for querying the session
    // ApiKey is a string representing a GUID
    .AddRemoteAppServer(options => options.ApiKey = ConfigurationManager.AppSettings["RemoteAppApiKey"])
    .AddSessionServer();

协议

Readonly

只读会话将从框架应用检索会话状态,而无需进行任何形式的锁定。 这由单个 GET 请求组成,该请求将返回会话状态,并且可以立即关闭。

Readonly session will retrieve the session state from the framework app

可写

可写会话状态协议的开头与只读相同,但在以下方面有所不同:

  • 需要其他 PUT 请求来更新状态
  • 初始 GET 请求必须保持打开状态,直到会话完成;如果关闭,会话将无法更新

Writeable session state protocol starts with the same as the readonly