如何 post 使用 VB.Net 中的 WebClient.UploadFileAsync 自定义 header

How to post a custom header with WebClient.UploadFileAsync in VB.Net

我的代码中有一个文件上传脚本,在上传时需要 post 身份验证密钥 header。但是,它似乎并没有像我预期的那样工作。到目前为止,这是我的代码:

Private Sub uploadFile()

    Dim address As String = "http://localhost/stripe/upload.php"

    Dim client As WebClient = New WebClient()
    Dim uri As Uri = New Uri(address)

    AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
    AddHandler client.UploadProgressChanged, AddressOf UploadProgressCallback

    client.Headers.Set("authKey", login.authKey)
    client.UploadFileAsync(uri, "POST", uploadFileName)

End Sub

Private Sub UploadProgressCallback(ByVal sender As Object, ByVal e As UploadProgressChangedEventArgs)
    ProgressBar1.Value = e.ProgressPercentage
    Label3.Text = String.Format("{0} / {1} kB", Math.Round(e.BytesSent / 1024), Math.Round(e.TotalBytesToSend / 1024))
    Label2.Text = String.Format("{0}%", e.ProgressPercentage)
    Application.DoEvents()
End Sub

Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As UploadFileCompletedEventArgs)
    Dim response As String = System.Text.Encoding.ASCII.GetString(e.Result)
    Console.WriteLine(response)
End Sub

当我运行这段代码:没有任何反应。输出控制台或其他任何地方都没有换行符。就像代码从未到达 UploadFileCompleted Sub 一样。它似乎也没有达到 UploadProgressCallback,因为进度条和相关标签永远不会更新。

当我尝试注释掉 client.Headers.Set("authKey", login.authKey) 行时:文件似乎已上传,但完成后:我收到了预期的 403 禁止消息,因为我没有 authKey header设置.

我做错了什么?

我发现了我的问题。问题是由于调用它的线程无法访问 login.authKey。由于该程序是多线程的:我必须确保线程可以访问它。当我使其可访问时:该功能按预期工作。

希望这对我身后的其他人有所帮助。 :)