代码之家  ›  专栏  ›  技术社区  ›  user6395764

HttpContext。响应电流为空。重定向扩展方法

  •  2
  • user6395764  · 技术社区  · 7 年前

    我有一个asp。框架4.6.1上的net项目。HttpContext。正常流量下电流正常。但如果我使用响应。重定向“Extension”方法HttpContext。此处的电流为空。

    对于正常响应。重定向它工作正常。我已经应用了不同的解决方案,比如在没有异步/等待方法的情况下检查它,但行为是相同的。

    有什么想法吗?

      public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
    {
    
        if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
        {
            response.Redirect(url);
        }
        else
        {
    
            Page page = (Page)HttpContext.Current.Handler;
    
            if (page == null)
            {
                throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
            }
            url = page.ResolveClientUrl(url);
    
            string script;
            if (!String.IsNullOrEmpty(windowFeatures))
            {
                script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
            }
            else
            {
                script = @"window.open(""{0}"", ""{1}"");";
            }
            script = String.Format(script, url, target, windowFeatures);
            ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Aristos    7 年前

    了解它的名称非常重要。如果没有调用此命令的页面,那么yes为null,它为null,因为没有页面来写入重定向命令(以及其中的其他命令)。

    例如,如果从新线程(而不是页面)调用它,则为null。

    如果从调用,也可以得到此错误 global.asax 在它的某些部分。

        2
  •  0
  •   user6395764    7 年前

    乔尔·哈克斯 注释修复了我的问题

    为什么不使用:此HttpContext上下文而不是此HttpResponse 使用反模式的响应:HttpContext。现在的

    创建HttpContext的扩展方法解决了该问题。

    public static void Redirect(this HttpContext context, string url, string target, string windowFeatures)
    {
    
        if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
        {
            context.Response.Redirect(url);
        }
        else
        {
    
            Page page = (Page)context.CurrentHandler;//HttpContext.Current.Handler;
    
            if (page == null)
            {
                throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
            }
            url = page.ResolveClientUrl(url);
    
            string script;
            if (!String.IsNullOrEmpty(windowFeatures))
            {
                script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
            }
            else
            {
                script = @"window.open(""{0}"", ""{1}"");";
            }
            script = String.Format(script, url, target, windowFeatures);
            ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
        }
    }