我有以下方法返回给定Http status code
的{{1}}:
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);
}
/ 200
等,但对于404
代码,我认为返回的结果是已经重定向({ {1}})结果,而不是应返回的实际301
,以及包含重定向指向位置的标题。
我在其他.Net Web请求类中看到过类似的内容,并且将某种200
属性设置为false。如果这是沿着正确的路线,有人能告诉我301
类的正确选择吗?
This post has info on the above allowAutoRedirect concept I mean
否则,我怎么能让这个方法返回allowAutoRedirect
而不是HttpClient
我知道真正的301s
的网址?
答案 0 :(得分:50)
我发现这样做的方法是创建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))
{
}
有关详细信息,请参阅here。