简体   繁体   中英

How to upload data with Microsoft.Net.Http?

In the past I made a class that shunk the request on an endpoint . Now, I create a dll that include this method, this is the code that I'm trying to convert on this library:

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);
}

In the not portable library System.Net I can call client.UploadData , but here I see only : postAsync and putAsync, there is a method that independent from the put or post request allow me to send the data from the client to the server ? Thanks in advance.

In an HTTP request PUT and POST are the correct ways to transmit data to a server, it does not make sense to send data independently of these methods. When you are using a client such as that available in System.Net this is merely being abstracted away from you.

In your old code you used some method passed in method parameter to send data with UploadData method, and it was probably POST or PUT . If you do not specify the method for UploadData , POST is being used. So you should use PostAsync or PutAsync , based on you current code and the value of method parameter you pass to UploadData .

The simplest way would be to use something like this:

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

The code for PUT would be the same, but with PutAsJsonAsync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM