我有一个关于框架 4.6.1 的 asp.net 项目。HttpContext.Current 在正常流程中很好。但是如果我使用Response.Redirect"Extension"方法HttpContext.Current在那里是空的。
对于正常的响应重定向,它工作正常。我已经应用了不同的解决方案,例如在没有异步/等待方法等的情况下检查它,但行为是相同的。
知道吗?
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);
}
}
了解您在哪里称呼它非常重要。如果没有页面调用它,那么 yes 是空的,它的空是因为没有页面来编写重定向命令(以及那里的其他命令(。
例如,如果从新线程(而不是页面(调用它,则为 null。
此外,如果您从它的某些部分中global.asax
调用它,则会收到此错误。
乔尔·哈克斯的评论解决了我的问题
为什么不使用:这个 HttpContext 上下文而不是这个 HttpResponse 反模式响应:HttpContext.Current?
创建 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);
}
}