如何避免“无法在页面回调中调用Response.Redirect”

时间:2009-10-08 15:59:57

标签: c# asp.net asp.net-ajax exception-handling response.redirect

我正在清理一些遗留框架代码,其中大量代码只是异常编码。不检查任何值以查看它们是否为空,因此会抛出并捕获大量异常。

我已经清理了大部分内容,但是,有一些错误/登录/安全相关的框架方法正在做Response.Redirect,现在我们正在使用ajax,我们得到了很多“无法在Page回调中调用Response.Redirect。“如果可能的话,我想避免这种情况。

有没有办法以编程方式避免此异常?我正在寻找像

这样的东西
if (Request.CanRedirect)
    Request.Redirect("url");

注意,这也发生在Server.Transfer上,所以我希望能够检查我是否能够执行Request.Redirect或Server.Transfer。

目前,它只是这样做

try
{
    Server.Transfer("~/Error.aspx"); // sometimes response.redirect
}
catch (Exception abc)
{
    // handle error here, the error is typically:
    //    Response.Redirect cannot be called in a Page callback
}

4 个答案:

答案 0 :(得分:14)

你可以尝试

if (!Page.IsCallback)
    Request.Redirect("url");

或者如果你没有页面方便......

try
{
    if (HttpContext.Current == null)
        return;
    if (HttpContext.Current.CurrentHandler == null)
        return;
    if (!(HttpContext.Current.CurrentHandler is System.Web.UI.Page))
        return;
    if (((System.Web.UI.Page)HttpContext.Current.CurrentHandler).IsCallback)
        return;

    Server.Transfer("~/Error.aspx");
}
catch (Exception abc)
{
    // handle it
}

答案 1 :(得分:6)

我相信您可以简单地将Server.Transfer()替换为在回调期间有效的Response.RedirectLocation()

try
{
    Response.RedirectLocation("~/Error.aspx"); // sometimes response.redirect
}
catch (Exception abc)
{
    // handle error here, the error is typically:
    //    Response.Redirect cannot be called in a Page callback
}

答案 2 :(得分:1)

您应该加载ScriptManager或ScriptManagerProxy,然后检查IsInAsyncPostBack标志。这看起来像这样:

ScriptManager sm = this.Page.Form.FindControl("myScriptManager") as ScriptManager;
if(!sm.IsInAsyncPostBack)
{
    ...
}

通过执行此操作,您可以将异步回发(应该无法重定向)与正常回发混合使用,我假设您仍然希望重定向。

答案 3 :(得分:1)

如上所述,但扩展为包含 .NET 4.x版本,并在没有Response.RedirectLocation可用时分配给Page属性。

try 
{
    HttpContext.Current.Response.Redirect("~/Error.aspx");
}
catch (ApplicationException) 
{
    HttpContext.Current.Response.RedirectLocation =    
                         System.Web.VirtualPathUtility.ToAbsolute("~/Error.aspx");
}
相关问题