简体   繁体   中英

Shopping cart session state done right in ASP.NET MVC

I'm implementing a simple session cart for unauthenticated users in ASP.NET MVC and I want to do it right.

In the past I have always stored the cart ID in the persistent Session["CartID"] store and as a cookie. Whenever I need to display the cart, I'll look up the user's cart items from my Carts and CartItems tables. But inside I know a more strongly-typed approach would be cleaner.

After Googling for the latest session MVC stuff, I found the term HttpSessionStateWrapper , which seems to be a testable way of dealing with sessions. But I have not found any good tutorials or standardised implementations. Maybe it's just a buzz-word and I should be sticking to Session["..."] .

What is the right way to implement a shopping cart using sessions in the latest version of ASP.NET MVC?

Steve Sanderson, in his book Pro ASP.NET MVC 2 Framework, gives a nice example of a how to implement a shopping cart using session in ASP.NET MVC. If you don´t have the book, you can get an idea reading here . It is a very neat approach. The idea is to create a model binder that takes the shopping cart from the session. The actions that use the shopping cart will get the cart "injected" by the model binder. When you´re testing those methods, your tests should be responsible for passing the shopping cart to the action.

MVC uses a testable and mockable abstraction of the HttpContext class called HttpContextBase. You don't need the wrapper at all and can still mock and unittest your controllers just fine.

First example I found on google: http://weblogs.asp.net/andrewrea/archive/2009/08/10/mocking-the-session-object-with-moq-inside-asp-net-mvc-and-having-a-clean-builder-method-for-session-values-in-the-controller.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM