0

I need some clarity about session and how to add objects, because I think I do it the wrong way.

First I create a session to hold a list of Products:

Session["ShoppingCart"] = new List<Products>();

To add Products to the list, I do like this:

Session["ShoppingCart"] = new Products { ID = productId, Name = name };

I guess this isn't the right way?

front-back
  • 257
  • 1
  • 7
  • 13
  • Possible duplicate of [ASP.net, adding objects to a session variable](http://stackoverflow.com/questions/8056323/asp-net-adding-objects-to-a-session-variable) – terbubbs Feb 09 '16 at 20:38

2 Answers2

4

I guess this isn't the right way?

Yes, this isn't the right way (please skip towards the last paragraph of my answer to know the correct way - which is not to use ASP.NET session at all). The correct way is to first get the object you stored inside the session by trying it to cast it to the same .NET type yo uhave stored inside the session:

var products = Session["ShoppingCart"] as List<Products>;

and then if this item is not null add the corresponding product to the list. We should of course make the necessary type check that the session actually contained a value with the specified key and that this value is of the expected type:

if (products != null)
{
    var product = new Products { ID = productId, Name = name };
    products.Add(product);
}

Of course we are using object references here which will only work if you are storing your session in-memory (sessionState mode = InProc) which of course is absolutely a terrible disaster and something you should never do in production. In a production environment you are probably persisting your session in a session server or even SQL server, aren't you? In this case it is more than obvious that working with object references is a recipe for disaster. So in this case once you have added the new product to the session you should of course set back the new list value to the session which will serialize the object instance to the corresponding data store:

if (products != null)
{
    var product = new Products { ID = productId, Name = name };
    products.Add(product);
    Session["ShoppingCart"] = products;
}

Now, after all this being said I must admit that using ASP.NET Session is probably the huge mistake you would ever commit in a real world application. So basically every time you are using Session["xxx"] you are doing it wrong. Simply search the entire solution for the Session keyword and just get rid of it.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for your answer! If I'm understanding what you are saying, I should not use Sessions for a shopping cart and instead store each cart item in a SQL table? I'm learning ASP.NET MVC and this is not a real project. – front-back Feb 09 '16 at 20:45
  • 1
    I never said that you should use a SQL table. What I said in my answer is that you should never use ASP.NET Session in a real world application - which is not the same thing. A SQL table is just one of the many ways to handle a shopping cart in a real world application that is hosted on may web servers. – Darin Dimitrov Feb 09 '16 at 20:46
  • OK, but why is Session so bad and I'm not sure what the alternative is? – front-back Feb 09 '16 at 20:47
  • An ASp.NET session basically enforces you to use SQL server or even worse a Session State Server (which is a single point of failure). As alternatives you might want to consider some of the NoSQL data stores that exist today. Of course I am only talking about real world applications. If you are doing just some learning stuff then feel more than free to use ASP.NET Sessions - they might even work in your case. I just wanted to point it out in my answer in case somebody is using this in a real app. – Darin Dimitrov Feb 09 '16 at 20:48
  • I'm not sure I follow you and your thoughts about Sessions in ASP.NET, but your code in the answer worked perfect! Thanks! – front-back Feb 09 '16 at 20:51
  • My thoughts about sessions in ASP.NET are that you should never use `Session["xxx"]` in a real world application. It's as simple as that. – Darin Dimitrov Feb 09 '16 at 20:52
  • OK, but thats the only thing I have learned so far, but I would like to use other options if that is better, but right know I'm not understand what is the better option to use Session[xxx]? – front-back Feb 09 '16 at 20:55
  • @DarinDimitrov And what about `UserInfo` storred in session? Is that a bad practice? – teo van kot Feb 09 '16 at 21:13
  • @teovankot, yes, in a real world application it's a disaster. It's good enough for learning and playing around in POCs though. – Darin Dimitrov Feb 09 '16 at 21:15
  • @DarinDimitrov but is there any real alternative? I mean if i need presist user login. – teo van kot Feb 09 '16 at 21:16
  • @teovankot, of course that there are: there are so many distributed data stores nowadays that it shouldn't really be a problem picking one :-) – Darin Dimitrov Feb 09 '16 at 21:19
  • Session variables do not persist in a web server farm. They are server variables and one server may service one request and another server may service the next request. The next server will not have your Session variable and then you get an error. You can either set your session to use SQL sessions or you use cookies on the client browser. Just be sure to not store sensitive data in the cookie such as user login information. – Trucktech Feb 09 '16 at 21:51
0

In order to add itens to an existing list on the Session, you must first retrieve the list then add the object to it. Here's an example:

Session["ShoppingCart"] = new List<Products>();
List<Products> productsList = (List<Products>)Session["ShoppingCart"];
productsList.add(new Products { ID = productId, Name = name });
Session["ShoppingCart"] = productsList;