【问题标题】:Does Response.RedirectPermanent(); process code after it is calledResponse.RedirectPermanent();调用后处理代码
【发布时间】:2014-08-27 17:00:28
【问题描述】:

我有以下代码检查异常,如果是 404 异常,它将检查 url 列表以查看页面是否已移动,如果匹配,将发出永久重定向到新页面:

    protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();
        if (exception != null)
        {
            if (exception is HttpException)
            {
                TryRedirect((HttpException)exception);
            }

            LogError(exception);
        }
    }

    private void TryRedirect(HttpException httpException)
    {
        if (httpException.GetHttpCode() == 404)
        {
            WebsiteRedirect redirect = SiteCache.Redirects.FirstOrDefault(x => string.Compare(x.LegacyURL, HttpContext.Current.Request.RawUrl, true) == 0);

            if (redirect != null)
            {
                // 301 it to the new url
                Response.RedirectPermanent(redirect.NewURL);
            }
        }
    }

现在我希望在重定向发生后,不会执行它之后的代码,即不会调用LogError 函数。但这似乎是因为我收到了找不到页面的错误消息。

这是 MVC Response.RedirectPermanent 的标准行为吗?

【问题讨论】:

    标签: asp.net-mvc-4 redirect http-status-code-301


    【解决方案1】:
    Response.RedirectPermanent(string url, bool endResponse);
    return null;
    

    【讨论】:

    • 我不明白这如何回答“调用重定向后会发生什么”的问题。
    【解决方案2】:

    当您使用response.RedirectPermanent() 时,它将完全委托请求。它不会执行或处理Response.RedirectPermanent(redirect.NewURL) 语句之后的任何语句。 如果您使用 Response.RedirectPermanent(string,boolean) 方法,然后将布尔值设置为 true,那么它将执行您的 logerror(exception)

    我请求你通过这个链接http://www.stepforth.com/blog/2008/redirects-permanent-301-vs-temporary-302/#.U7pxUfmSx-M

    【讨论】:

    • 那么为什么在 RedirectPermanent 之后会调用 LogError 函数呢?
    • 它永久重定向请求,即你不会从你调用的地方取回控制权
    • 进一步阅读 RedirectPermanent 是完全错误的,它将继续处理响应,除非您告诉它不要这样做 - 它需要一个额外的布尔值到方法中,如果设置为 true 将终止当前回复。如果设置为 false,它将完成当前响应。默认设置为 false
    • Response.RedirectPermanent(url) 将调用 Response.RedirectPermanent(url, false) 意味着它将处理之后的所有内容
    • 是的,我同意。因为默认值为 false。 @皮特
    【解决方案3】:

    好吧,事实证明这是标准行为,因为 RedirectPermanent 有 2 个重载(我在 VS 播放时从未见过第二个重载):

    Response.RedirectPermanent(string url);
    Response.RedirectPermanent(string url, bool endResponse);
    

    endResponse 选项表示永久重定向将继续完成响应或在重定向后立即结束进程。

    默认设置为 false,这意味着第一个重载(这是我使用的)将完成响应,这就是它调用 LogError 函数的原因

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2011-11-03
      • 2010-12-02
      • 2023-03-10
      • 2018-06-19
      • 1970-01-01
      相关资源
      最近更新 更多