Search code examples
c#.net-corewebclient

Get Response Headers From WebClient


I'm trying to upload a file using WebClient, but I can't seem to find a way to get the response headers once the file is uploaded I'm using this Microsoft example to get the headers, but it just returns null. My code looks like this:

public void UploadPart(string filePath, string preSignedUrl)
{
   WebClient wc = new();
   wc.UploadProgressChanged += WebClientUploadProgressChanged;
   wc.UploadFileCompleted += WebClientUploadCompleted;
   wc.UploadFileAsync(new Uri(preSignedUrl), "PUT", filePath);

   // Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
   WebHeaderCollection myWebHeaderCollection = wc.ResponseHeaders;

   System.Diagnostics.Debug.WriteLine(myWebHeaderCollection);
}

I can confirm that the headers exist because I'm able to get them using an HttpWebResponse upload implementation in another method.


Solution

  • Method should be written like this.

    public Task UploadPart(string filePath, string preSignedUrl)
    {
       WebClient wc = new();
       wc.UploadProgressChanged += WebClientUploadProgressChanged;
       wc.UploadFileCompleted += WebClientUploadCompleted;
       await wc.UploadFileAsync(new Uri(preSignedUrl), "PUT", filePath);
    
       // Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
       WebHeaderCollection myWebHeaderCollection = wc.ResponseHeaders;
    
       System.Diagnostics.Debug.WriteLine(myWebHeaderCollection);
    }
    

    Replace void with Task. Use await in UploadFileAsyn because it may possible without request complete code jump to next line.