biasedbit
biasedbit

Reputation: 2870

Get HTTP headers in asynchronous WebClient request

I'm using System.Net.WebClient to perform some HTTP operations in asynchronous mode. The reason to use asynchronous operations is, above anything else, the fact that I get progress change indications - which is only available for async operations, as stated by the docs.

So let's say I have my WebClient set up:

this.client = new WebClient();
this.client.UploadStringCompleted +=
    new UploadStringCompletedEventHandler(textUploadComplete);

and the delegate:

private void textUploadComplete(Object sender, UploadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        // trigger UI failure notification
        return;
    }

    // FIXME not checking for response code == 200 (OK)
    // trigger UI success notification
}

So you see, I'm assuming that if no exception is raised, the requests was always successful (which may not be the case, since the HTTP response status code can be != 2xx). From the documentation on UploadFileAsync I can't tell if a non-200 response is processed as well.

I'm really new to C# and I can't seem to find a way to access the headers for that particular asynchronous request's response. Seems to me that each WebClient can only hold a response (or a set of headers) at any given time.

While I'm not going to be executing multiple parallel requests at the same time, I'd still like to know if there is a more elegant way of retrieving a particular request's response headers/status code, rather than having to get the "last-available" response from the WebClient.

Thanks.

Upvotes: 8

Views: 6100

Answers (2)

Ramin
Ramin

Reputation: 87

get headers from the sender object i just added one line to your code above

  private void textUploadComplete(Object sender, UploadStringCompletedEventArgs e)
        {
            var headers = (sender as WebClient)?.ResponseHeaders; //HEADERS
            if (e.Error != null)
            {
                // trigger UI failure notification
                return;
            }

            // FIXME not checking for response code == 200 (OK)
            // trigger UI success notification
        }

Upvotes: 1

TCC
TCC

Reputation: 2596

Are you in .NET 4.5? If so try using the TaskAsync overloads ... you would still need to access the headers from WebClient instance, but I wouldn't find this objectionable at all using the TAP workflow ... I agree it feels a little wrong to do it in an ordinary event handler.

await client.UploadStringTaskAsync(...); 
var headers = client.ResponseHeaders; 

Best of all you can do it all on the UI thread ... won't block ... so your 'trigger update UI' is really just 'Update UI'.

Upvotes: 0

Related Questions