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

All*_*ice 13 c# asp.net response.redirect exception-handling asp.net-ajax

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

我有但是大多数清理,有一些错误/登录/安全相关的框架,正在做Response.Redirect的,现在,我们正在使用AJAX的方法,我们得到的ALOT 的Response.Redirect"不能被称为在页面回调中." 如果可能的话,我想避免这种情况.

有没有办法以编程方式避免此异常?我正在寻找类似的东西

if (Request.CanRedirect)
    Request.Redirect("url");
Run Code Online (Sandbox Code Playgroud)

注意,这也发生在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
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*don 15

你可以试试

if (!Page.IsCallback)
    Request.Redirect("url");
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)


Whe*_*ill 7

如上所述,但扩展为包括.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");
}
Run Code Online (Sandbox Code Playgroud)


小智 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
}
Run Code Online (Sandbox Code Playgroud)

  • 作为记录,我发现 (ASP.NET 4.x) a) `Response.RedirectLocation` 是一个属性而不是一个方法,并且 b) 它没有扩展 `~` 符号,所以你需要 `Response.RedirectLocation = Page.ResolveUrl("~/Error.aspx")`。 (3认同)