4

如何使用 HTTP PUT 方法发送字节数组?AddFile类的方法RestRequest发送额外的标头。方法AddParameter采用Object类型。

我是怎么做的:

byte[] data;
using (var ms = new MemoryStream())
{
    Serializer.Serialize(ms, query);
    data = ms.ToArray();
    ms.Close();
}
var client = new RestClient(ServerPath);
var request = new RestRequest(RequestPath, Method.PUT);
request.AddFile("stream", x => new MemoryStream(data), string.Empty);
client.ExecuteAsync(request, responce => Debug.WriteLine(responce.Content));

但是在服务器端,我看到了额外的标头

-------------------------------------------28947758029299 内容处置:表单数据;名称=“流”;filename="" Content-Type: application/octet-stream [RAW DATA HERE] -------------------------------28947758029299 --

额外的标题使查询不可读。我做错了什么?

4

2 回答 2

5

感谢马克·格拉维尔。解决方案:

        var client = new HttpClient();
        var httpContent = new ByteArrayContent(data);
        client.PutAsync(Path, httpContent);
于 2013-02-25T14:03:50.630 回答
1

我有时会为此苦苦挣扎,最后找到了解决方案,魔术是作为没有参数名称的请求体给出

// file to send
IFormFile file
byte[] buffer;

using (var ms = new MemoryStream())
using (var stream = file.OpenReadStream())
{
    stream.CopyTo(ms);
    buffer = ms.ToArray();
}
var uploadDoc = new RestRequest("ressource", Method.POST);
uploadDoc.RequestFormat = DataFormat.None;
uploadDoc.AddParameter("", buffer, ParameterType.RequestBody);

var response = new RestClient("baseUrl").Execute(uploadDoc);

希望它可以帮助别人

于 2020-07-10T19:11:13.503 回答