0

I have the following C# method that accepts a URL as an input and returns the text data that exists at that location:

public string GetWebData(string uri)
{
    string response = string.Empty;
    try
    {
        var request = WebRequest.Create(uri);
        request.BeginGetResponse(result =>
        {
            var httpRequest = (HttpWebRequest)result.AsyncState;
            var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(result);

            using (var reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                response = reader.ReadToEnd();
            }
        }, request);
    }
    catch (WebException)
    {
        response = string.Empty;
    }
    return response;
}

However, the reader.ReadToEnd(); method returns an empty string. I'm not sure if I'm doing anything wrong, since the method seems to be syntactically identical to all the tutorials I've consulted. What am I doing wrong?

miguelarcilla
  • 1,426
  • 1
  • 20
  • 38

1 Answers1

1

You're returning response immediately - even though the callback which assigns a useful value to response will only fire later. Do you understand how BeginGetResponse works? It would be worth studying the documentation and examples carefully.

Why are you using asynchronous methods if you actually want to return the value as soon as the method finishes? If asynchronous methods are all you've got (e.g. you're on Windows Phone) then you should stick with that asynchronous idiom - don't try to make it synchronous.

As an aside, swallowing exceptions like this is a really bad idea too - you should almost never continue as if everything's okay, and even if you do want to ignore the error as far as the user experience is concerned, you should almost certainly be logging the exception.

Additionally, when you fetch the response you should use a using statement as WebResponse implements IDisposable.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm working on a Windows Phone project, and all the examples I've been looking at follow that template to some degree. I'll read up on the BeginGetResponse method, though, and see how I can modify this. And thanks for the tip regarding exceptions, I'm just trying to get the response to show up before I proceed. – miguelarcilla Sep 22 '13 at 16:38
  • @miguelarcilla: "To some degree" is probably the key part - I bet they either take a callback, or attempt to wait for the result (which is a bad idea in itself). Basically Windows Phone is designed for asynchrony, and you should work with that rather than trying to fake synchronous IO. – Jon Skeet Sep 22 '13 at 16:42
  • Got it. I don't know if I have the answer yet, but I think I'm getting on the right track. Thanks :) – miguelarcilla Sep 22 '13 at 16:49