如何将控制器与 Http 上下文会话解耦

发布于 2024-10-26 11:03:24 字数 70 浏览 2 评论 0原文

我需要在我的操作中的会话中存储一些数据,但是我担心将控制器耦合到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

场罚期间 2024-11-02 11:03:24

不,这不值得。控制器可以访问包括会话在内的 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 the Session object to them.

書生途 2024-11-02 11:03:24

特别是对于 ApiControllers,您可以自己构建一个 DelegatingHandler 并将所有好东西推送到 request.Properties 上。然后,无论您是在测试还是实时运行,您都可以从您的请求中检索它们。好处是您对控制器中的会话具有零依赖性。

MessageHandler

public class ContextHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        // get the goodies to add onto the request
        var goodies = /* call to goodieGoodieYumYum */


        // add our goodies onto the request
        request.Properties.Add(Constants.RequestKey_Goodies, goodies);

        // pass along to the next handler
        return base.SendAsync(request, cancellationToken);
    }
}

控制器操作

var goodies = (List<Goodie>)Request.Properties[Constants.RequestKey_Goodies];

Especially for ApiControllers, build yourself a DelegatingHandler and push all of your goodies onto request.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

public class ContextHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        // get the goodies to add onto the request
        var goodies = /* call to goodieGoodieYumYum */


        // add our goodies onto the request
        request.Properties.Add(Constants.RequestKey_Goodies, goodies);

        // pass along to the next handler
        return base.SendAsync(request, cancellationToken);
    }
}

Controller Action

var goodies = (List<Goodie>)Request.Properties[Constants.RequestKey_Goodies];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文