C# Obtaining data from WebRequest not returning values

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow