Permanent redirection

Hi Mythz,

I have a RawHttpHandler implementation that checks whether a request is IPv4 or IPv6 and redirects to the corresponding host name if needed.

Next up the RedirectHttpHandler returns a Redirect (302) In this case I would like it to be a Permanent Redirect (301).

It would be nice to have a flag for RedirectHttpHandler to signal permanent redirection. Or is there a good reason why this is not a good idea?

Cheers,
Robert van Drunen

I have been looking at the HttpStatusCode enumerator values to actual status codes. And a bit confused.

Both Moved and MovedPermanently map to 301, Found and Redirect to 302 and TemporaryRedirect to 307.

There must be a really good story behind this.

What does your code look like that’s doing the redirect?

Not sure what the reasons for the multiple HttpStatusCode values is, maybe they thought friendlier aliases makes them easier to use.

The redirect code is quite simple:

  var request = req.OriginalRequest as HttpListenerRequest;

  if (request != null)
  {
    if (IsIPAddress(request.Url))
    {
      string correspondingHostName;

      if (RedirectMap.TryGetValue(request.LocalEndPoint.Address.ToString(), out correspondingHostName))
      {
        var builder = new UriBuilder(request.Url);

        builder.Host = correspondingHostName;
        
        return new RedirectHttpHandler { AbsoluteUrl = builder.ToString() };
      }
    }

    return null;
  }

  throw new HttpError(HttpStatusCode.BadRequest, "Cannot respond to request");

Returning the RedirectHttpHandler results in the 302 code being sent back to the client.

In my scenario I would want a permanent redirect / the 301 code.

I was thinking of something like:

return new RedirectHttpHandler { AbsoluteUrl = builder.ToString(), IsPermanent = true };

ok no worries I’ve made RedirectHttpHandler.StatusCode overridable in this commit which you can now use with:

return new RedirectHttpHandler { 
    AbsoluteUrl = builder.ToString(), 
    StatusCode =  HttpStatusCode.MovedPermanently
};

This change is available from v4.5.5 that’s now available on MyGet.

1 Like

Any idea when this change will be available on NuGet?

(I’ve got two changes in 4.5.5 that work fine on my dev machine but my co-workers only use the NuGet feed)

Thanks again for the quick response :smile:

That’s not going to be till next release which will be a while as we only just deployed last week. If you need it now you’ll need to fetch the pre-release packages that’s on MyGet.

But we’re frequently deploying .NET Core packages so if you move to .NET Core you can have it now :slight_smile:

Another temp solution is to take a local copy of the RedirectHttpHandler.cs and return your updated version.

1 Like