2

我需要在几个 ASPX 代码隐藏文件中测试一个条件,并且在某些情况下,我想完全绕过正常的页面加载过程,以便不加载相应的 ASPX 页面。Intead,我想向浏览器发送从代码隐藏方法编写的自定义响应。

有谁知道从哪里开始——在页面生命周期中覆盖哪些方法以及确保我的自定义 Response.Write 在正常 ASPX 页面内容被抑制时发送到浏览器的最佳技术?

谢谢。

4

3 回答 3

7

可能是最简单的方法 - 使用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...
    }
}
于 2009-04-08T21:32:21.580 回答
6

使用 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)
{
    如果(自定义响应)
    {
        Response.Write("我正在发送自定义回复");
        this.Context.ApplicationInstance.CompleteRequest();
        返回; // 绕过正常处理。
    }
    // 正常处理...
}

受保护的覆盖无效渲染(HtmlTextWriter writer)
{
    如果 (!customResponse)
        base.Render(作家); // 然后像往常一样写页面。
}
于 2011-05-04T02:43:05.467 回答
0

这真的取决于你在回应什么,它是一个发布的表单字段、身份验证信息等......?使用 Page_Load 显示的方法将起作用,但页面生命周期中该点之前的任何内容也将执行。

于 2009-04-08T21:41:40.653 回答