Search code examples
asp.netsessiondotvvm

How do I create a session variable in DotVVM viewmodel?


I am building a site in DotVVM and when I try the following line of code but I get error: NullReferenceException

HttpContext.Current.Session.Add ("Value", Item3);

Solution

  • DotVVM is an OWIN middleware, so you have to configure OWIN first to enable session. First, you need to declare this method, which turns on ASP.NET session:

    public static void RequireAspNetSession(IAppBuilder app) {
        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);
    }
    

    Then in the Startup.cs file, call it:

    app.RequireAspNetSession();
    

    Then you can use HttpContext.Current.Session["key"] to access your session state.