使用HttpClient,如何防止自动重定向并获取原始状态代码并在301 的情况下转发Url

我有以下方法返回给定UrlHttp status code

 public static async void makeRequest(int row, string url) { string result; Stopwatch sw = new Stopwatch(); sw.Start(); try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = new HttpResponseMessage(); response = await client.GetAsync(url); // dump contents of header Console.WriteLine(response.Headers.ToString()); if (response.IsSuccessStatusCode) { result = ((int)response.StatusCode).ToString(); } else { result = ((int)response.StatusCode).ToString(); } } } catch (HttpRequestException hre) { result = "Server unreachable"; } sw.Stop(); long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)); requestComplete(row, url, result, time); } 

它适用于404等,但是在301代码的情况下,我认为返回的结果是已经重定向的200 )结果,而不是应该返回的实际301以及包含重定向的位置的头部会被指出。

我在其他.Net Web请求类中看到了类似的东西,并且有一种技术可以将某种allowAutoRedirect属性设置为false。 如果这是沿着正确的路线,有人能告诉我HttpClient类的正确替代方案吗?

这篇文章有关于上面的allowAutoRedirect概念的信息,我的意思是

另外,我怎么能让这个方法为我知道真正的301s返回301s而不是200s

我发现这样做的方法是创建一个HttpClientHandler实例并将其传递给HttpClient的构造函数

 public static async void makeRequest(int row, string url) { string result; Stopwatch sw = new Stopwatch(); sw.Start(); // added here HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.AllowAutoRedirect = false; try { // passed in here using (HttpClient client = new HttpClient(httpClientHandler)) { } 

有关详细信息,请参见此处