Rob*_*nik 4 asp.net-mvc httpcontext cloning
克隆当前请求的HttpContext实例最简单的方法是什么?
我正在开发Asp.net MVC v1中的应用程序.我将常规的PartialView功能升级为实际上具有非常相似的子控制器,但具有自己的上下文.使用PartialViews时,必须在主视图的控制器操作中填充局部视图的视图数据.我创建了自己的功能,可以从视图中调用控制器操作.这样我得到:
问题是每个子控制器请求都使用HttpContext.因此,当我在子控制器中设置一些HttpContext.Item时,它实际上填充了实际请求的HttpContext.
这就是我想要克隆HttpContext的原因.我已经在使用:
HttpContext subContext = new HttpContext(request, response);
// what happened to Session, User, Items etc. properties?
Run Code Online (Sandbox Code Playgroud)
但这并没有设置除请求和响应之外的任何内容.但我可能还需要其他属性和集合......如会话,项目,用户......等.
虽然"不可能"的答案是正确的,但有一种替代方法比将值写入当前上下文然后重写回其原始状态要清晰得多.解决方案是完全基于您选择的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...
}
Run Code Online (Sandbox Code Playgroud)
参考:https://github.com/maartenba/MvcSiteMapProvider/issues/278#issuecomment-34905271
| 归档时间: |
|
| 查看次数: |
5658 次 |
| 最近记录: |