我在使用 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。请注意,它可能需要配置。 在我的例子中是:
3) 使用你的 session 。请记住,如果没有为 session 设置任何值,则每个请求的 SessionID 都是不同的。 因此,您必须为 session 添加一些值。这就是它在多个请求中保持不变的方式。
希望对您有所帮助。
关于c# - 如何使用 Owin 托管存储 session 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30781264/