c# - 如何使用 Owin 托管存储 session 数据?

标签 c# session owin middleware httpcontext

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

场景:

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

对象 HTTPContext 为空。

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

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

有人知道如何在 Owin session 中存储登录数据吗?

下面是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;
        }
    }
}

最佳答案

我也遇到过一些与 session 有关的问题。

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

1) 添加 NuGet Microsoft.AspNetCore.Session

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

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

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

希望对您有所帮助。

关于c# - 如何使用 Owin 托管存储 session 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30781264/

相关文章:

c# - ASP.NET:为无 cookie session 实现 ISessionIDManager?

rest - 服务器如何知道不记名 token 是否有效而不将其存储在磁盘或内存中

rest - 如何在自托管的 o​​win 服务器中动态创建 Web API(REST api)?

c# - Automapper 自定义解析器

c# - OpacityMask 无法按预期在 C# 代码中工作

android - { session 状态 :OPENING, token :{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:1xxxxxxxxxxx}

session - 使 Grails 中过滤单元测试的 session 无效

c# - 在 MVC View 中使用 Razor 循环模型属性

c# - C# 是否有任何方法可以在按下按钮时执行 Javascript 函数?

c# - 没有 Owin 的 Asp.Net MVC 5?