如何使用Owin托管存储会话数据?

Tho*_*n04 8 c# session middleware httpcontext owin

我在使用Owin托管的应用程序中创建会话时遇到问题.我尝试过使用RedisSession,但我不知道如何配置它所以它给了我一个错误.我找了一段时间的解决方案,尝试了不同的东西,最后决定在这里寻求帮助.

场景:

  • 我正在使用HTTP POST请求登录应用程序,
  • 用户登录名和密码应存储在会话中,
  • 对于每个需要先前登录会话的下一个GET/POST请求为空(登录名和密码为空).

对象HTTPContext是空的.

我正在使用Ninject进行依赖注入.

我尝试过类似的东西:OWIN中间件可以使用http会话吗?

有没有人知道如何在Owin会话中存储登录数据?

下面是Owin配置文件,其中包含的东西都来自上面发布的链接.

[assembly: OwinStartup(typeof(Service.Startup))]
namespace Service
{
public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }
                );
            appBuilder.RequireAspNetSession();
            appBuilder.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config);

        }

        public static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel(new Module());
            return kernel;
        }
    }
    public static class AspNetSessionExtensions
    {
        public static IAppBuilder RequireAspNetSession(this IAppBuilder app)
        {
            app.Use((context, next) =>
            {
                // Depending on the handler the request gets mapped to, session might not be enabled. Force it on.
                HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
                httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
                return next();
            });
            // SetSessionStateBehavior must be called before AcquireState
            app.UseStageMarker(PipelineStage.MapHandler);
            return app;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ana*_*ich 0

我在会议上也遇到了一些困难。

这是对我有用的解决方案:

1)添加NuGet Microsoft.AspNetCore.Session

2) 在IServiceCollection上调用.AddSession。请注意,它可能需要配置。就我而言,它是: 在此输入图像描述

3) 使用您的会话。请记住,如果没有为会话设置值,则每个请求的 SessionID 都是不同的。所以你必须为会话添加一些价值。这就是它在多个请求中保持不变的方式。

这是我的会话固定中间件: 在此输入图像描述

希望能帮助到你。