如何避免“Response.Redirect不能在页面回调中调用” [英] How to avoid "Response.Redirect cannot be called in a Page callback"

查看:926
本文介绍了如何避免“Response.Redirect不能在页面回调中调用”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理一些遗留的框架代码,其中很大一部分是按照异常编码。没有检查值是否为空,因此抛出并捕获了大量的异常。



我已经清理了大部分内容,但是,有几个错误/登录/安全相关的框架方法正在做Response.Redirect,现在我们是使用ajax,我们正在获得ALOT的Response.Redirect不能在页面回调中调用。如果可能,我想避免这种情况。



有没有办法以编程方式避免这种异常?我正在寻找类似

  if(Request.CanRedirect)
Request.Redirect(url);

请注意,这也是Server.Transfer发生的,所以我想要检查如果我能够执行Request.Redirect OR Server.Transfer。



目前,它只是这样做

  try 
{
Server.Transfer(〜/ Error.aspx); //有时response.redirect
}
catch(异常abc)
{
//在这里处理错误,错误通常是:
// Response.Redirect不能在页面回调中调用
}


解决方案

你可以尝试

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

或者如果没有页面便利...

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

Server.Transfer(〜/ Error.aspx);
}
catch(异常abc)
{
//处理
}


I'm cleaning up some legacy framework code and a huge amount of it is simply coding by exception. No values are checked to see if they are null, and as a result, copious amounts of exceptions are thrown and caught.

I've got most of them cleaned up, however, There are a few error / login / security related framework methods that are doing Response.Redirect and now that we are using ajax, we are getting ALOT of "Response.Redirect cannot be called in a Page callback." And I'd like to avoid this if at all possible.

Is there a way to programatically avoid this exception? I'm looking for something like

if (Request.CanRedirect)
    Request.Redirect("url");

Note, this is also happening with Server.Transfer, so I'd like to be able to check if I am able to do Request.Redirect OR Server.Transfer.

Currently, its simply doing this

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
}

解决方案

You can try

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

or if you dont have a Page handy...

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
}

这篇关于如何避免“Response.Redirect不能在页面回调中调用”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆