Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 386
biasedbit Avatar asked Oct 13 '10 10:10

biasedbit


People also ask

How do I add a custom header in webclient?

Method SummarySet the media type of the body, as specified by the Content-Type header. Add a cookie with the given name and value. Copy the given cookies into the entity's cookies map. Perform the request without a request body.


1 Answers

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
        }
like image 148
Ramin Avatar answered Oct 30 '22 04:10

Ramin