HttpContext.Current.Session is null + OWIN

前端 未结 1 504
执念已碎
执念已碎 2021-02-04 10:02

I\'m entirely new to OWIN and this issue has been a major blocker for me.

Basically, at my MVC app I have the following at Startup class:

public partial          


        
相关标签:
1条回答
  • 2021-02-04 10:39

    You're almost there. The reason your session is still null is that you have not instructed OWIN to initialize System.Web Sessions prior to your middleware is beeing executed.

    By adding .UseStageMarker(..) after your middleware registration you'll tell OWIN where in the execution pipline it should perform SetSessionStateBehaviour

    app.Use((context, next) =>
    {
        var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
        httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
        return next();
    });
    
    // To make sure the above `Use` is in the correct position:
    app.UseStageMarker(PipelineStage.MapHandler);
    

    By default, Owin Middleware run at the last event (PipelineStage.PreHandlerExecute) which is too late for you in this case.

    Now, to use sessions, you need to work in a second middleware, that runs after the session has been Aquired by the Asp.Net runtime. This middleware must be run in the PostAquireState phase, like so:

    .Use((context, next) =>
     {
         // now use the session
         HttpContext.Current.Session["test"] = 1;
    
         return next();
    })
    .UseStageMarker(PipelineStage.PostAcquireState);
    

    Asp.Net katana docs has an excellent article on how the middleware works. See the PiplineStage enum docs and the HttpApplication docs for details on the execution order in Asp.net.

    0 讨论(0)
提交回复
热议问题