Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 994
Tomáš Jurásek Avatar asked Apr 20 '16 08:04

Tomáš Jurásek


1 Answers

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.

like image 98
Tomáš Herceg Avatar answered Dec 02 '22 03:12

Tomáš Herceg