5

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);

2 Answers2

8

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.

Tomáš Herceg
  • 1,595
  • 1
  • 13
  • 18
0

You can save an object in the Session by doing:

Session["Value"] = Item3;

You can retrieve an object from the Session by doing:

object value = Session["Value"];

Usually, you need to cast the value to the type you used, so if Item3 is a string, then you would do:

string value = (string)Session["Value"];

You can access session variables from your views as well, so you shouldn't need to store it in your viewmodel.

Lars Kristensen
  • 1,410
  • 19
  • 29