问题描述
我正在尝试使用 WebClient 上传文件,但是一旦文件上传我似乎无法找到获取响应标头的方法我正在使用 this Microsoft example 获取标头,但是它只返回空值。我的代码如下所示:
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);
}
我可以确认标头存在,因为我可以通过另一种方法使用 HttpWebResponse 上传实现来获取它们。
解决方法
方法应该这样写。
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);
}
用任务替换无效。 在 UploadFileAsyn 中使用 await 因为它可能不需要请求完整的代码跳转到下一行。