gpt4 book ai didi

asp.net-mvc - 是否可以复制/克隆 Web 请求的 HttpContext

转载 作者:行者123 更新时间:2023-12-03 18:25:04 25 4
gpt4 key购买 nike

克隆当前请求的 HttpContext 实例的最简单方法是什么?

我正在 Asp.net MVC v1 中开发一个应用程序。我将常规的 PartialView 功能升级为实际上具有行为非常相似但有自己的上下文的子 Controller 。当您使用 PartialViews 时,您必须在主 View 的 Controller 操作中为分部 View 填充 View 数据。我创建了自己的功能,可以从 View 中调用 Controller 操作。这样我得到:

  • 我不必在主 View 的 Controller 操作中提供 subview 的数据
  • 子 Controller 方法可以操作更封装的数据,而与其他 View / Controller 没有任何关系

  • 问题是每个子 Controller 请求都使用HttpContext。因此,当我在子 Controller 中设置一些 HttpContext.Item 时,它实际上填充了实际请求的 HttpContext。

    这就是我想克隆 HttpContext 的原因。我已经在使用:
    HttpContext subContext = new HttpContext(request, response);
    // what happened to Session, User, Items etc. properties?

    但这除了请求和响应之外没有设置任何其他内容。但我可能还需要其他属性和集合......比如 session 、项目、用户......等。

    最佳答案

    虽然“不可能”的答案是正确的,但有一种替代方法比将值写入当前上下文然后重写回其原始状态要干净得多。解决方案是创建一个完全基于您选择的 URL 的新 HttpContext 对象。

    // A new request/response is constructed to using a new URL.
    // The new response is using a StreamWriter with null stream as a backing stream
    // which doesn't consume resources

    using (var nullWriter = new StreamWriter(Stream.Null))
    {
    var newRequestUri = new Uri("http://www.somewhere.com/some-resource/");
    var newRequest = new HttpRequest("", newRequestUri.ToString(), newRequestUri.Query);

    var newResponse = new HttpResponse(nullWriter);
    var newContext = new HttpContextWrapper(new HttpContext(newRequest, newResponse));

    // Work with the new context here before it is disposed...
    }

    引用: https://github.com/maartenba/MvcSiteMapProvider/issues/278#issuecomment-34905271

    关于asp.net-mvc - 是否可以复制/克隆 Web 请求的 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1466804/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com