[英]How to upload data with Microsoft.Net.Http?
In the past I made a class that shunk the request on an endpoint
. 过去,我制作了一个在
endpoint
上缩减请求的类。 Now, I create a dll
that include this method, this is the code that I'm trying to convert on this library: 现在,我创建一个包含此方法的
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);
}
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
? 在非便携式库
System.Net
我可以调用client.UploadData
,但是在这里我只能看到:postAsync和putAsync,有一种方法独立于put
或post
请求,使我可以将数据从client
发送到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. 在HTTP请求中,PUT和POST是将数据传输到服务器的正确方法,而独立于这些方法发送数据是没有意义的。 When you are using a client such as that available in System.Net this is merely being abstracted away from you.
当您使用诸如System.Net中可用的客户端时,这仅仅是从您身上抽象出来的。
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
. 在您的旧代码中,您使用了一些传入
method
参数的方法来通过UploadData
方法发送数据,它可能是POST
或PUT
。 If you do not specify the method for UploadData
, POST
is being used. 如果未为
UploadData
指定方法,则使用POST
。 So you should use PostAsync
or PutAsync
, based on you current code and the value of method
parameter you pass to UploadData
. 所以,你应该用
PostAsync
或PutAsync
,根据您当前的代码和值method
参数传递给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
PUT的代码将相同,但使用
PutAsJsonAsync
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.