有人可以解释为什么我的代码中的属性IsRequestBeingRedirected
始终为false,以及如何正确重定向以获得真值?
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (filterContext.RequestContext.HttpContext.Response.IsRequestBeingRedirected)
{
//some another logic
}
//some code
filterContext.RequestContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Url.AbsolutePath);
}
答案 0 :(得分:2)
在调用IsRequestBeingRedirected
期间,Response.Redirect
属性设置为true 。这是通过.NET Reflector的源代码:
public void Redirect(string url)
{
this.Redirect(url, true, false);
}
public void Redirect(string url, bool endResponse)
{
this.Redirect(url, endResponse, false);
}
internal void Redirect(string url, bool endResponse, bool permanent)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.IndexOf('\n') >= 0)
{
throw new ArgumentException(System.Web.SR.GetString("Cannot_redirect_to_newline"));
}
if (this._headersWritten)
{
throw new HttpException(System.Web.SR.GetString("Cannot_redirect_after_headers_sent"));
}
Page page = this._context.Handler as Page;
if ((page != null) && page.IsCallback)
{
throw new ApplicationException(System.Web.SR.GetString("Redirect_not_allowed_in_callback"));
}
url = this.ApplyRedirectQueryStringIfRequired(url);
url = this.ApplyAppPathModifier(url);
url = this.ConvertToFullyQualifiedRedirectUrlIfRequired(url);
url = this.UrlEncodeRedirect(url);
this.Clear();
if (((page != null) && page.IsPostBack) && (page.SmartNavigation && (this.Request["__smartNavPostBack"] == "true")))
{
this.Write("<BODY><ASP_SMARTNAV_RDIR url=\"");
this.Write(HttpUtility.HtmlEncode(url));
this.Write("\"></ASP_SMARTNAV_RDIR>");
this.Write("</BODY>");
}
else
{
this.StatusCode = permanent ? 0x12d : 0x12e;
this.RedirectLocation = url;
if (UriUtil.IsSafeScheme(url))
{
url = HttpUtility.HtmlAttributeEncode(url);
}
else
{
url = HttpUtility.HtmlAttributeEncode(HttpUtility.UrlEncode(url));
}
this.Write("<html><head><title>Object moved</title></head><body>\r\n");
this.Write("<h2>Object moved to <a href=\"" + url + "\">here</a>.</h2>\r\n");
this.Write("</body></html>\r\n");
}
// IsRequestBeingRedirected is set here
this._isRequestBeingRedirected = true;
EventHandler redirecting = Redirecting;
if (redirecting != null)
{
redirecting(this, EventArgs.Empty);
}
if (endResponse)
{
this.End();
}
}
因此,在致电Response.Redirect
后,您必须检查该值是否为真。
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//some code
filterContext.RequestContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Url.AbsolutePath);
if (filterContext.RequestContext.HttpContext.Response.IsRequestBeingRedirected)
{
//some another logic
}
}
当然,你的逻辑不是很清楚。您已经知道您正在重定向,因为您正在调用Response.Redirect
,因此在这种情况下检查此属性似乎是多余的。