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 Answers 2

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.

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.

2
  • In classic asp.net yes, but i'm using new asp.net framework dotVVM. I'm wrote it later sorry. Apr 20, 2016 at 9:03
  • @TomášJurásek Ah, my bad - I didn't notice the dotvvm tag. Apr 20, 2016 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.