我有一个像这样的vb.net异步httpResponse函数:
Public Async Function getWebserviceResponse(ByVal sb As StringBuilder, ByVal baseUri As Uri, ByVal Method As String, ByVal User As String, ByVal Password As String) As Task(Of HttpResponseMessage)
Dim client As HttpClient = New HttpClient()
client.BaseAddress = baseUri
Dim authHeader As AuthenticationHeaderValue = New AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
String.Format("{0}:{1}", User, Password))))
client.DefaultRequestHeaders.Authorization = authHeader
Dim content As New StringContent(sb.ToString, System.Text.Encoding.UTF8, "application/json")
Dim resp As HttpResponseMessage
Dim cancellationToken As CancellationToken
If Method = "Post" Then
resp = Await client.PostAsync(baseUri, content, cancellationToken)
ElseIf Method = "Put" Then
resp = Await client.PutAsync(baseUri, content, cancellationToken)
End If
Return resp
End Function
问题是,“resp”应该返回一个“正常”的HttpResponseMessage而不是一个Task(Of HttpResponseMessage)......
我怎么能得到这个?提前感谢您的帮助!
祝你好运 马丁
答案 0 :(得分:1)
resp
HttpResponseMessage
。但是,该方法是Async
。请注意方法签名:
Public Async Function getWebserviceResponse(...) As Task(Of HttpResponseMessage)
因此,当代码在逻辑上返回HttpResponseMessage
时,方法技术上会返回Task(Of HttpResponseMessage)
。这与其中调用的方法完全相同。请注意:
resp = Await client.PostAsync(baseUri, content, cancellationToken)
PostAsync
方法返回Task(Of HttpResponseMessage)
,但该行代码将HttpResponseMessage
放入resp
变量。这是因为使用了Await
关键字。
要实现相同的行为,任何调用getWebserviceResponse()
方法的方法都应该这样做:
someVariable = Await getWebServiceResponse(...)
修改:根据您的评论,您可以使用以下代码:
Dim myStreamReader As New StreamReader(webserviceResponse.getWebserviceResponse(....).Content.ReadAsStreamAsync().Result)
我怀疑应该更改为使用Await
关键字:
Dim myStreamReader As New StreamReader(Await (Await webserviceResponse.getWebserviceResponse(....)).Content.ReadAsStreamAsync())
或者,把它分解成一些不那么混乱的东西:
Dim responseMessage As HttpResponseMessage = Await webserviceResponse.getWebserviceResponse(....)
Dim responseStream As Stream = Await responseMessage.Content.ReadAsStreamAsync()
Dim myStreamReader As New StreamReader(responseStream)
需要等待每个单独的异步操作。