Using WebClient in C# is there a way to get the URL of a site after being redirected?

If I understand the question, it’s much easier than people are saying – if you want to let WebClient do all the nuts and bolts of the request (including the redirection), but then get the actual response URI at the end, you can subclass WebClient like this:

class MyWebClient : WebClient
{
    Uri _responseUri;

    public Uri ResponseUri
    {
        get { return _responseUri; }
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        _responseUri = response.ResponseUri;
        return response;
    }
}

Just use MyWebClient everywhere you would have used WebClient. After you’ve made whatever WebClient call you needed to do, then you can just use ResponseUri to get the actual redirected URI. You’d need to add a similar override for GetWebResponse(WebRequest request, IAsyncResult result) too, if you were using the async stuff.

Leave a Comment