代码之家  ›  专栏  ›  技术社区  ›  Allen Rice 0x6A75616E

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

  •  12
  • Allen Rice 0x6A75616E  · 技术社区  · 16 年前

    我正在清理一些遗留的框架代码,其中大量代码只是通过异常进行编码。不检查任何值以查看它们是否为null,因此会引发和捕获大量异常。

    如果可能的话,我想避免这种情况。

    有没有办法通过编程避免这种异常?我在找像这样的东西

    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 回复  |  直到 16 年前
        1
  •  17
  •   Allen Rice 0x6A75616E    16 年前

    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
    }
    
        2
  •  8
  •   Curtis Rolando Quezada    14 年前

    我相信你可以简单地替换 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
    }
    
        3
  •  2
  •   WheretheresaWill    10 年前

    如上所述,但扩展到包括 .NET4.x版本 分配给 Response.RedirectLocation 当没有 Page 可获得的

    try 
    {
        HttpContext.Current.Response.Redirect("~/Error.aspx");
    }
    catch (ApplicationException) 
    {
        HttpContext.Current.Response.RedirectLocation =    
                             System.Web.VirtualPathUtility.ToAbsolute("~/Error.aspx");
    }
    
        4
  •  1
  •   Dan Monego    16 年前

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

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