我没有 REST API 经验。我继承了 .NET 4.7.1 C# 客户端/服务器,需要添加(大型)二进制文件传输功能。我无法使用 RestSharp。
在客户端,这就是我已经取得的进展:
HttpClient client = new HttpClient();
...
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(?); // TODO: What should I enter here?
using (var content = new MultipartFormDataContent())
{
var fileContent = new ByteArrayContent(bytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "My.dat"
};
content.Add(fileContent);
var response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
发布失败并显示:
Status Code: 500, ReasonPhrase: 'could not find expected boundary'
我并没有接受上述实现(在网上找到)。
在服务器端,如何从请求参数中提取字节?
public async Task ReceiveFile(
HttpListenerRequest request,
...)
{
...
if (request.HasEntityBody)
{
// TODO: Save bytes to a file
}
...
}
我仅限于获取 HttpListenerRequest 参数的处理程序。
受到 Bart Vanseer 在 Post byte array to Web API server using HttpClient 的回答的启发,我简化了我的客户端:
Client.DefaultRequestHeaders.Accept.Clear();
var url = @"myurl";
HttpContent binaryContent = new ByteArrayContent(bytes);
var response = await Client.PostAsync(url, binaryContent);
虽然 MultipartFormDataContent 可能是正确的方法,但我只是要附加一个查询字符串来传递一些上下文。
受到 Jon Skeet 在 C# save a file from a HTTP Response 的回答的启发,我实现了我的服务器:
...
if (request.HasEntityBody)
{
using (Stream output = File.OpenWrite(fullPath))
{
using (Stream input = request.InputStream)
{
input.CopyTo(output);
}
}
}
...