阅读量:0
要追踪重定向,可以使用HttpClientHandler
类来处理重定向。以下是一个示例代码:
using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { using (HttpClientHandler handler = new HttpClientHandler()) { handler.AllowAutoRedirect = false; // 禁止自动重定向 using (HttpClient client = new HttpClient(handler)) { HttpResponseMessage response = await client.GetAsync("https://example.com"); if (response.StatusCode == System.Net.HttpStatusCode.Found || // 302 response.StatusCode == System.Net.HttpStatusCode.MovedPermanently) // 301 { string redirectUrl = response.Headers.Location.AbsoluteUri; Console.WriteLine("Redirected to: " + redirectUrl); } } } } }
在此示例中,我们使用HttpClientHandler
类创建了一个带有禁止自动重定向功能的HttpClient
实例。当发送GET请求时,如果返回的状态码是302(Found)或301(Moved Permanently),则可以从响应头中获取重定向的URL。