2 asp.net page-lifecycle response.write
我需要在几个ASPX代码隐藏文件中测试一个条件,在某些情况下,我想完全绕过正常的页面加载过程,以便不加载相应的ASPX页面.Intead,我想向使用代码隐藏方法编写的浏览器发送自定义响应.
有谁知道从哪里开始 - 覆盖页面生命周期中的哪些方法以及确保在正常的ASPX页面内容被抑制时将我的自定义Response.Write发送到浏览器的最佳技术?
谢谢.
可能是最简单的方法 - 使用Page_Load().
protected void Page_Load(object sender, EventArgs e)
{
bool customResponse = true;
if (customResponse)
{
Response.Write("I am sending a custom response");
Response.End(); //this is what keeps it from continuing on...
}
}
Run Code Online (Sandbox Code Playgroud)
使用Response.End()执行此操作的"简单"方法对于性能而言非常糟糕,抛出一个终止该线程的异常.
http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx
http://weblogs.asp.net/hajan/archive /2010/09/26/why-not-to-use-httpresponse-close-and-httpresponse-end.aspx
我有同样的问题并以这种方式解决了.这是一个两步过程:首先调用HttpApplication.CompleteRequest()并退出处理.接下来重写Render(),以便不调用基本方法.然后示例代码变为:
bool customResponse = true;
protected void Page_Load(object sender, EventArgs e)
{
if (customResponse)
{
Response.Write("I am sending a custom response");
this.Context.ApplicationInstance.CompleteRequest();
return; // Bypass normal processing.
}
// Normal processing...
}
protected override void Render(HtmlTextWriter writer)
{
if (!customResponse)
base.Render(writer); // Then write the page as usual.
}