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

时间:2015-06-11 12:48:08

标签: c# session owin middleware httpcontext

我在使用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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我也遇到了一些困扰。

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

1)添加NuGet Microsoft.AspNetCore.Session

2)在您的 IServiceCollection 上调用 .AddSession 。注意,它可能需要配置。 以我为例: enter image description here

3)使用您的会话。请记住,如果没有为会话设置任何值,则每个请求的SessionID都不相同。 因此,您必须为会话增加一些价值。这样,它将在多个请求中保持不变。

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

希望有帮助。