要追蹤重定向,可以使用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。