如何将控制器与 Http 上下文会话解耦
我需要在我的操作中的会话中存储一些数据,但是我担心将控制器耦合到 http 上下文会话,我考虑过创建一个服务,但这真的值得吗?
I need to store some data in session inside my action however I'm concerned about coupling my controller to the http context session, I have thought about creating a service, but is it really worth it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这不值得。控制器可以访问包括会话在内的 Http 上下文。更不用说您已经在使用会话的抽象: HttpSessionStateBase 可以在单元测试中轻松模拟。
在某些情况下,您可以让业务方法采用 ICollection 作为输入参数,它是由 HttpSessionStateBase 实现的接口,然后让控制器将 Session 对象传递给它们。
No, it isn't worth it. It is the controller that has access to the Http Context including the session. Not to mention that you already are working with an abstraction of the session: HttpSessionStateBase which can be easily mocked in a unit test.
There might be situations where you could have your business methods take ICollection as input parameter which is an interface implemented by
HttpSessionStateBase
and then have the controller pass theSession
object to them.特别是对于
ApiControllers
,您可以自己构建一个DelegatingHandler
并将所有好东西推送到request.Properties
上。然后,无论您是在测试还是实时运行,您都可以从您的请求中检索它们。好处是您对控制器中的会话具有零依赖性。MessageHandler
控制器操作
Especially for
ApiControllers
, build yourself aDelegatingHandler
and push all of your goodies ontorequest.Properties
. You can then retrieve them from your request whether you are testing or running live. The benefit is that you then have zero dependency on Session in your Controller.MessageHandler
Controller Action