C# 使用 HttpClient,在 301 的情况下,我将如何防止自动重定向并获取原始状态代码和转发 Url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14731980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using HttpClient, how would I prevent automatic redirects and get original status code and forwading Url in the case of 301
提问by Gga
I have the following method that returns the Http status code
of a given Url
:
我有以下方法返回Http status code
给定的Url
:
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);
}
It works well for 200
/404
etc, however in the case of 301
codes I believe the returned result is the already-redirected(200
) result, rather than the actual 301
that should be returned and which would have a header containing where the redirect would be pointed to.
它适用于200
/404
等,但是在301
代码的情况下,我相信返回的结果是已经重定向的( 200
) 结果,而不是301
应该返回的实际结果,并且它会有一个包含重定向指向的标头。
I have seen something like this in other .Net web requests classes and the technique there was to set some sort of allowAutoRedirect
property to false. If this is along the right lines, can anyone tell me the correct alternative for the HttpClient
class?
我在其他 .Net web 请求类中看到过类似的东西,并且有将某种allowAutoRedirect
属性设置为 false 的技术。如果这是正确的路线,谁能告诉我该HttpClient
课程的正确替代方案?
This post has info on the above allowAutoRedirect concept I mean
这篇文章有关于上述 allowAutoRedirect 概念的信息,我的意思是
Else, how might I get this method to return 301s
rather than 200s
for Urls I know to be genuine 301s
?
否则,我怎样才能让这个方法返回301s
而不是200s
我知道是真实的 Urls 301s
?
采纳答案by Gga
I have found that the way to do this is by creating an instance of HttpClientHandler
and passing it in the constructor of HttpClient
我发现这样做的方法是创建一个实例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))
{
}
See herefor more info.
请参阅此处了解更多信息。