user1063108
user1063108

Reputation: 712

Asp.net HttpContext.Current.Items returning null

I am testing to build a asp.net web application. What I have is 3 web pages:

Default.aspx;
Home.aspx;
ThirdPage.aspx;

When user submits login data to Default.aspx, I retrieve user information from db, put it in a class and add it to Context like this

HttpContext.Current.Items.Add("UserData", userData);

Then I use Server.Transfer to send the request to Home.aspx. On Home.aspx, I have a link which points to ThirdPage.aspx. I click on this link and hoped that user information would be available here as well but it is not. Where as I was hoping to retain the userdata class across the user session across all pages in my web application until users session is expired . Can some one please guide? It is possibly a beginner question so please be kind. Thanks

Upvotes: 1

Views: 1710

Answers (2)

Cornelis
Cornelis

Reputation: 1107

I am unsure what the exact problem may be but I have some solutions that might work. If I am not mistaken you are trying to get user information over a couple of pages?

Here are some ways to get that done:

  1. Repeat the code you did on the first page that transfers the data to the second page and adapt it so it will work from the second to the third. This might work but I won't recommend because having to reuse and adapt the code each time you create a new page.
  2. The better one I think is to write your information to an XML file and deleting the file when the session expires. You can find how to write it here and reading it here.
  3. But my personal favorite is to have a static Class. Static classes can be acces from anywhere. As shown on the page here.

    public static class Globals

    {
        public static String name; 
        public static int age;
    
        public void SetName(){...}
        public void SetAge(){...}
        public String GetName(){...}
        public int GetName(){...}
    }
    
    • Just make it a mutable class (You can change the variables using functions) and it should be easy to get the user information across pages.

      1. Using JSON to save and load here are c# functions:

    public void SaveInfo(User user){

    //Convert to Json string json = JsonConvert.SerializeObject(user, Formatting.Indented);

    //Write to file, you will have to create a file serverside if you want
    //if you have a 
    File.WriteAllText(@"location.json", json);
    

    }

    public void LoadUser(){ using (StreamReader r = new StreamReader("Location.json")) { string json = r.ReadToEnd(); List items = JsonConvert.DeserializeObject>(json); }

Upvotes: 0

denys-vega
denys-vega

Reputation: 3697

Check ASP.NET Session State Overview

Usage:

Session["UserData"] = userData;

Upvotes: 1

Related Questions