WebClient in .NET is a handy class for network access, but sometimes you need things that it doesn’t expose “out of the box”. Fortunately it’s quite simple to extend.
One of the handy features of the class is that it automatically handles redirects on your behalf. Suppose that you make a request to some URI that returns an HTTP status code of 301 – if the AllowAutoRedirect property on WebClient is set, it will automatically parse the HTTP response and make a subsequent call to the redirected URL all by itself. Nice.
In my case however I wanted to find out the actual URL that it had redirected to, so I extended WebClient as below to always save the Uri that it was last getting a response from. This Uri would be different from the request Uri if the server had returned an HTTP status code indicating redirection.
public class MyWebClient : WebClient
{
Uri _responseUri;
public Uri ResponseUri
{
get { return _responseUri; }
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.AllowAutoRedirect = true;
return request;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
_responseUri = response.ResponseUri;
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
_responseUri = response.ResponseUri;
return response;
}
}
0 comments:
Post a Comment