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

问题描述 投票:8回答:1

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

场景:

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

对象HTTPContext是空的。

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

我尝试过类似的东西:Can OWIN middleware use the http session?

有没有人知道如何在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;
        }
    }
}
c# session owin middleware httpcontext
1个回答
0
投票

我也有过一些挣扎的会议。

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

1)添加NuGet Microsoft.AspNetCore.Session

2)在IServiceCollection上调用.AddSession。注意,它可能需要配置。在我的情况下它是:enter image description here

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

这是我的会话固定中间件:enter image description here

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.