Getting the Redirected URL from the Original URL

前端 未结 9 1483
终归单人心
终归单人心 2020-12-05 14:57

I have a table in my database which contains the URLs of some websites. I have to open those URLs and verify some links on those pages. The problem is that some URLs get red

9条回答
  •  遥遥无期
    2020-12-05 15:14

    Async HttpClient versions:

    // works in .Net Framework and .Net Core
    public static async Task GetRedirectedUrlAsync(Uri uri, CancellationToken cancellationToken = default)
    {
        using var client = new HttpClient(new HttpClientHandler
        {
            AllowAutoRedirect = false,
        }, true);
        using var response = await client.GetAsync(uri, cancellationToken);
    
        return new Uri(response.Headers.GetValues("Location").First();
    }
    
    // works in .Net Core
    public static async Task GetRedirectedUrlAsync(Uri uri, CancellationToken cancellationToken = default)
    {
        using var client = new HttpClient();
        using var response = await client.GetAsync(uri, cancellationToken);
    
        return response.RequestMessage.RequestUri;
    }
    

    P.S. handler.MaxAutomaticRedirections = 1 can be used if you need to limit the number of attempts.

提交回复
热议问题