I'm trying to perform some HEAD checks using System.Net.Http.HttpClient. It works great on everything except 301 redirects. In that case, HttpClient says the status 200, even though the server said 301 and gave a new Location.
Here's a quick test to validate what I'm seeing:
[Test]
public async void Test301Capture()
{
const string url = "http://www.youtube.com/"; // http://www.youtube.com/ does a 301 to https://www.youtube.com/
var httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
using (var client = new HttpClient(httpClientHandler))
using (var headRequest = new HttpRequestMessage(HttpMethod.Head, url))
using (var headResponse = await client.SendAsync(headRequest))
{
Log.InfoFormat("Result of HEAD check on \"{0}\" is: {1}", url, headResponse.StatusCode); // *should* be a 301
Assert.AreNotEqual(200, (int)headResponse.StatusCode); // *fails* because StatusCode *is* 200
}
}
Output from the above is:
Result of HEAD check on "http://www.youtube.com/" is: OK
I know the server is saying 301 because a quick HEAD check using Advanced REST Client to test http://www.youtube.com/ says:
Redirect
To:https://www.youtube.com/ with status: 301 Show explanation HTTP/1.1 301 Moved Permanently
Redirection information has not been cached.
Date: Tue, 01 Apr 2014 20:08:09 GMT
Server: gwiseguy/2.0
Content-Length: 0
Cache-Control: no-cache
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Expires: Tue, 27 Apr 1971 19:44:06 EST
X-XSS-Protection: 1; mode=block; report=https://www.google.com/appserve/security-bugs/log/youtube
Location: https://www.youtube.com/
Alternate-Protocol: 80:quic
I did find this answer, Using HttpClient, how would I prevent automatic redirects and get original status code and forwading Url in the case of 301, however my results are different.