如何创建新的 HttpContext?
public void getContent() {
string VirtualPath = "~/Content.aspx";
var page = BuildManager.CreateInstanceFromVirtualPath( VirtualPath, typeof( Page ) ) as IHttpHandler;
page.ProcessRequest( HttpContext.Current );
}
我使用该函数从不同文件加载内容,但“page.ProcessRequest( HttpContext.Current )”在当前上下文中插入内容,而我需要的是返回指定文件内容的函数。
我想知道是否有一种工作方法可以创建新的 HttpContext,以便“page.ProcessRequest”不会在当前响应中插入任何内容。
public void getContent() {
string VirtualPath = "~/Content.aspx";
var page = BuildManager.CreateInstanceFromVirtualPath( VirtualPath, typeof( Page ) ) as IHttpHandler;
page.ProcessRequest( HttpContext.Current );
}
I'm using that function to load the content from different files, but the "page.ProcessRequest( HttpContext.Current )" inserts the content at the current context, and what I need is the function to return the content of the specified file.
I wonder if there's a working way to create a new HttpContext, so that "page.ProcessRequest" don't insert anything into the current response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,奥德是正确的。您无法轻松创建自己的 HttpContext 实例。但是,您仍然可以通过其他方式实现您的目标。
使用服务器.执行。 http://msdn.microsoft.com/en-us/library/ms150027.aspx 。
您可以指定要与 TextWriter 一起执行的 HttpHandler 以将内容转储到其中。
Oded is correct as far as I know. You can't easily create your own instance of the HttpContext. However you can still achieve your goals thorugh other means.
Use a Server.Execute. http://msdn.microsoft.com/en-us/library/ms150027.aspx.
You can specify the HttpHandler to execute along with a TextWriter to dump the content into.
如果没有大量的解决方法,您就无法创建新的 HttpContext。
这是 ASP.NET 和 BCL 的缺点之一 - 使 Web 应用程序无法测试(或者至少在没有 HttpContext 的情况下很难测试。
我不清楚您的要求
我需要的是返回指定文件内容的函数
- 您能准确解释一下您的意思吗?You can't create a new
HttpContext
, not without lots of work arounds.It is one of the failings of ASP.NET and the BCL - makes web applications untestable (or at least very difficult to test without
HttpContext
.I am not clear on your requirement
what I need is the function to return the content of the specified file
- can you please explain exactly what you mean by that?查看 Pex/Moles 它包含一个模拟框架,可以模拟几乎任何类型或成员,即使其是密封的或静态的。
(它通过使用自定义测试主机来做到这一点)
Check out Pex/Moles its includes a mocking framework that can mock almost any type or member, even if its sealed or static.
(it does this by using a custom test host)