WebHelper for Desktop CLR

By on 4/4/2011

I recently posted a nice little helper class that I had been using on windows phone 7. This version works on the desktop CLR (there's a minor difference in how you create a web request) ... and also adds a new method that lets you get direct access to the response stream. So I figured I'd post it as it is a generally useful class.
public static class WebHelper
{
    public static WaitHandle Get(string url, Action<WebResponse> action)
    {
        return Get(new Uri(url), action);
    }

public static WaitHandle Get(Uri uri, Action<WebResponse> action) { var request = WebRequest.CreateDefault(uri); ManualResetEvent handle = new ManualResetEvent(false); request.BeginGetResponse(i => { var response = request.EndGetResponse(i); action(response); handle.Set(); }, null);

return handle; }

public static WaitHandle Get(string url, Action<string> action) { return Get(new Uri(url), action); }

public static WaitHandle Get(Uri uri, Action<string> action) { return Get(uri, response => { var sreader = new StreamReader(response.GetResponseStream()); var result = sreader.ReadToEnd(); action(result); }); } }
For some example usage, you can easily proxy a download through an ASP.NET MVC web app:
        public ActionResult Get(string q)
        {
            Stream res = new MemoryStream();
            string contentType = "text/html";

bool timedOut = !WebHelper .Get(q, html => { res = html.GetResponseStream(); contentType = html.ContentType; }) .WaitOne(30000); // wait 30 seconds to get a response

if (timedOut) { StreamWriter writer = new StreamWriter(res); writer.WriteLine("The request timed out, sorry!"); res.Seek(0, SeekOrigin.Begin); }

return File(res, contentType); }

See more in the archives