簡體   English   中英

如何使用WebClient通過[FromBody] POST到WebAPI

[英]How to use WebClient to POST to WebAPI using [FromBody]

簡而言之,我需要發送一個byte[]數組作為主體值。 問題是[FromBody]始終為null。 到目前為止,我所看到的所有解決方案都涉及將傳遞的值以一種或另一種方式傳遞給字符串。 如果傳遞的原始內容是純文本(ascii),這很好,但是在我發送(例如)jpg的情況下,這是行不通的。

意識到並知道由於某種原因我不能使用HTTPClient以任何形式添加它,這在各個地方都破壞了解決方案,這一點非常重要。 我一直在使用WebClient。

這是我下面的代碼:

呼叫頁面:

Private Function UploadFile(targetURL As String, fileAttachment As Byte()) As String
    Dim retVal As String = String.Empty
    Using client = New WebClient()
        Try                
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(targetURL), HttpWebRequest)
            request.Method = "POST"
            request.ContentType = "application/x-www-form-urlencoded"
            request.ContentLength = fileAttachment.Length

            Dim requestStream As Stream = request.GetRequestStream()
            requestStream.Write(fileAttachment, 0, fileAttachment.Length)

            Dim response As WebResponse = request.GetResponse()
            Dim respStream As Stream = response.GetResponseStream()
            Dim reader As New StreamReader(respStream)

            retVal = reader.ReadToEnd()
            respStream.Dispose()
            reader.Dispose()
        Catch ex As WebException
            If ex.Status = WebExceptionStatus.ProtocolError Then
                Dim wbrsp As HttpWebResponse = CType(ex.Response, HttpWebResponse)
                Throw New HttpException(CInt(wbrsp.StatusCode), wbrsp.StatusDescription)
            Else
                Throw New HttpException(500, ex.Message)
            End If
        End Try
    End Using
    Return retVal
End Function

WebAPI方法:

    [Route("Upload/{appName}/{appKey}/{fileName}/{fileExt}")]
    public async Task<string> Post(string appName, string appKey, string fileName, string fileExt, [FromBody] byte[] values) { 
//snip as rest is not needed since values is always null

什么是合理的解決方案,以使字節數組不轉換為字符串(具有“破壞”值的效果)?

解決方案是違反直覺的:

//targetURL As String, fileAttachment As Byte(), fileName As String, fileExtension As String
//you don't send the data to the webapi action. You WRITE to it like it's a file        
Using client = New WebClient()
    Try
        client.Headers.Add("Content-Type", "application/octet-stream")
        Using requestStream As Stream = client.OpenWrite(New Uri(targetURL), "POST")
            requestStream.Write(fileAttachment, 0, fileAttachment.Length)
        End Using    
    Catch ex As WebException
        If ex.Status = WebExceptionStatus.ProtocolError Then
            Dim wbrsp As HttpWebResponse = CType(ex.Response, HttpWebResponse)
            Throw New HttpException(CInt(wbrsp.StatusCode), wbrsp.StatusDescription)
        Else
            Throw New HttpException(500, ex.Message, New Exception("File upload failed."))
        End If
    End Try
End Using

還有WebAPI的神奇代碼:

byte[] values = await Request.Content.ReadAsByteArrayAsync(); 

您不會考慮將數據發送到URL的方式就不會像寫入文件那樣,因為您只是不這樣做,但是它可以工作,並且字節流在過程中的任何地方都不會轉換為字符串(如果源不是純ascii,則流不會被“損壞”。

當然,這樣做的最大問題是,無論如何設置WebAPI操作以返回數據,OpenWrite方法都不會返回任何內容。 因此,您可以做的就是在出現問題時拋出異常。 如果您需要返回數據,則只需編寫另一個操作來檢索從第一次調用中創建的數據(在這種情況下,是上載和保存的文件的唯一ID)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM