购物车会话状态在 ASP.NET MVC 中正确完成
我正在 ASP.NET MVC 中为未经身份验证的用户实现一个简单的会话购物车,我希望做得正确。
过去,我总是将购物车 ID 存储在持久 Session["CartID"]
存储中并作为 cookie。每当我需要显示购物车时,我都会从我的 Carts
和 CartItems
表中查找用户的购物车项目。但在内部,我知道更强类型的方法会更干净。
在谷歌搜索最新的会话 MVC 内容后,我发现了术语 HttpSessionStateWrapper,它似乎是处理会话的可测试方法。但我还没有找到任何好的教程或标准化的实现。也许这只是一个流行词,我应该坚持使用 Session["..."]
。
在最新版本的 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Steve Sanderson 在他的《Pro ASP.NET MVC 2 Framework》一书中给出了一个很好的示例,说明如何在 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 使用 HttpContext 类的可测试且可模拟的抽象,称为 HttpContextBase。您根本不需要包装器,仍然可以很好地模拟和单元测试您的控制器。
我在谷歌上找到的第一个例子:
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
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