Pete
Pete

Reputation: 58442

Does Response.RedirectPermanent(); process code after it is called

I have the following code which checks an exception and if it is a 404 exception, it will check a list of urls to see if the page has been moved and if it matches, will issue a permanent redirect to the new page:

    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);
            }
        }
    }

Now I would expect that after the redirect has happened, non of the code after it would be executed ie the LogError function wouldn't be called. But it seems to be as I am getting error messages for the pages not being found.

Is this standard behaviour for MVC Response.RedirectPermanent?

Upvotes: 3

Views: 1964

Answers (3)

boateng
boateng

Reputation: 898

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

Upvotes: -1

Nadendla
Nadendla

Reputation: 722

When you are using response.RedirectPermanent() it will completely delegates the request.It's not going to execute or process any statement after Response.RedirectPermanent(redirect.NewURL) statement. If you use Response.RedirectPermanent(string,boolean) method then give boolean value to true then it will execute your logerror(exception)

I request you to go through this link http://www.stepforth.com/blog/2008/redirects-permanent-301-vs-temporary-302/#.U7pxUfmSx-M

Upvotes: -1

Pete
Pete

Reputation: 58442

Ok so as it turns out this is the standard behaviour as RedirectPermanent has 2 overloads (I never saw the second overload as my VS was playing up):

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

The option of endResponse says that the permanent redirect will continue to finish the response or end the process immediately after the redirect.

The default is set to false meaning that the first overload (which is what I have used) will finish the response which is why it is calling the LogError function

Upvotes: 4

Related Questions