C# 如何避免;响应。无法在页面回调中调用重定向;

C# 如何避免;响应。无法在页面回调中调用重定向;,c#,asp.net,asp.net-ajax,exception-handling,response.redirect,C#,Asp.net,Asp.net Ajax,Exception Handling,Response.redirect,我正在清理一些遗留的框架代码,其中大量代码只是通过异常进行编码。不检查任何值以查看它们是否为null,因此会引发和捕获大量异常 我已经清理了其中的大部分,但是,有一些与错误/登录/安全相关的框架方法正在执行Response.Redirect。现在我们使用ajax,我们得到了很多“Response.Redirect不能在页面回调中调用。”,如果可能的话,我希望避免这种情况 有没有办法通过编程避免这种异常?我在找像这样的东西 if (Request.CanRedirect) Request.

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

我已经清理了其中的大部分,但是,有一些与错误/登录/安全相关的框架方法正在执行Response.Redirect。现在我们使用ajax,我们得到了很多“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
}
你可以试试

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
}

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

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

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

我相信您可以简单地将
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
}

如上所述,但扩展为包括.NET 4.x版本,并在没有
页面
可用时分配给
响应.RedirectLocation
属性

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

在HttpContext.Current中的何处可以找到IsCallback?我不会总是有一个页面啊,找到了,我在你的答案中添加了我最终使用的代码,因为你的代码片段是我真正需要的。我真不敢相信我自己没有想到这么简单的事情,呵呵。感谢manhrm,您能详细说明它与Page.IsCallback之间的区别吗?看起来区别在于IsCallback适用于Asp.net ICallbackEventHandler接口,而IsInAsyncPostBack适用于基于UpdatePanel的更改。这是我能找到的它们之间最直接的比较:您也可以使用ScriptManager.GetCurrent(第页);作为记录,我发现(ASP.NET 4.x)a)
Response.RedirectLocation
是一个属性而不是一个方法,b)它不扩展
~
符号,因此需要
Response.RedirectLocation=Page.ResolveUrl(“~/Error.aspx”)