Home > Blockchain >  C# HttpClient Detect Redirect
C# HttpClient Detect Redirect

Time:11-09

I need to detect when there is a redirect. My first thought was to check the status code for 301, but for:

var link = "https://grnh.se/8dc368b82us?s=LinkedIn&source=LinkedIn";
var responseMessage = await httpClient.GetAsync(link);

responseMessage returns "OK" but in the browser this link returns 301 and redirects.

Link redirects

So if I can't rely on this, then I decided to just compare the request URI to the response URI.

GetAsync returns a Task<HttpResponseMessage> but HttpResponseMessage does not have a property for the response URI.

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpresponsemessage?view=net-5.0

System.Net.WebResponse contains a property for the response URI, but can I use this with HttpClient? or must I use WebRequest for the request?

https://docs.microsoft.com/en-us/dotnet/api/system.net.webresponse?view=net-5.0

Is there a better way?

Note: This will be scanning millions of links, so I'd prefer to instantiate one HttpClient. Microsoft recommends using HttpClient rather than WebRequest: https://docs.microsoft.com/en-us/dotnet/api/system.net.webresponse?view=net-5.0

CodePudding user response:

You can disable automatic redirect like this:

var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var link = "https://grnh.se/8dc368b82us?s=LinkedIn&source=LinkedIn";
var responseMessage = await httpClient.GetAsync(link);

Then you can check for redirect comparing responseMessage.StatusCode with common redirect codes:

MovedPermanently = 301
Redirect = 302
TemporaryRedirect = 307

New location will be in responseMessage.Headers.Location and you can request for it again if you need.

  • Related