簡體   English   中英

如何使用Microsoft.Net.Http上傳數據?

[英]How to upload data with Microsoft.Net.Http?

過去,我制作了一個在endpoint上縮減請求的類。 現在,我創建一個包含此方法的dll ,這是我要在此庫上轉換的代碼:

using (var client = new HttpClient())
{
     string requestJson = JsonConvert.SerializeObject(data);
     client.DefaultRequestHeaders.Add("token", token);
     byte[] responseArray = client. 'there is no upload data method
     // the bottom code is of the old method 
     byte[] responseArray = client.UploadData(requestURI, method, Encoding.UTF8.GetBytes(requestJson));
    return Encoding.ASCII.GetString(responseArray);
}

在非便攜式庫System.Net我可以調用client.UploadData ,但是在這里我只能看到:postAsync和putAsync,有一種方法獨立於putpost請求,使我可以將數據從client發送到server 提前致謝。

在HTTP請求中,PUT和POST是將數據傳輸到服務器的正確方法,而獨立於這些方法發送數據是沒有意義的。 當您使用諸如System.Net中可用的客戶端時,這僅僅是從您身上抽象出來的。

在您的舊代碼中,您使用了一些傳入method參數的方法來通過UploadData方法發送數據,它可能是POSTPUT 如果未為UploadData指定方法,則使用POST 所以,你應該用PostAsyncPutAsync ,根據您當前的代碼和值method參數傳遞給UploadData

最簡單的方法是使用如下所示的內容:

using(var client = new HttpClient())
{
    var response = await client.PostAsJsonAsync(requestUrl, data);
    return await response.Content.ReadAsStringAsync();
}

PUT的代碼將相同,但使用PutAsJsonAsync

暫無
暫無

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

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