问题描述
我不知道我怎么可以发送一个压缩文件到的WebAPI控制器,反之亦然。
的问题是,我的WebAPI使用JSON来传输数据。一个zip文件不可序列化,无论是流。一个字符串是序列化的。但是,必须有一个其他的解决办法,而不是压缩转换为字符串,比发送字符串。这听起来是错误的。
I'm wondering how I can send a zip file to a WebApi controller and vice versa.The problem is that my WebApi uses json to transmit data. A zip file is not serializable, either is a stream. A string would be serializable. But there has to be an other solution than to convert the zip into a string and than send the string. That just sounds wrong.
任何想法如何做到这一点?
Any idea how this is done?
推荐答案
如果您的API方法需要一个的Htt prequestMessage
,那么你可以从拉流:
If your API method expects an HttpRequestMessage
then you can pull the stream from that:
public HttpResponseMessage Put(HttpRequestMessage request)
{
var stream = GetStreamFromUploadedFile(request);
// do something with the stream, then return something
}
private static Stream GetStreamFromUploadedFile(HttpRequestMessage request)
{
// Awaiting these tasks in the usual manner was deadlocking the thread for some reason.
// So for now we're invoking a Task and explicitly creating a new thread.
// See here: http://stackoverflow.com/q/15201255/328193
IEnumerable<HttpContent> parts = null;
Task.Factory
.StartNew(() => parts = request.Content.ReadAsMultipartAsync().Result.Contents,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default)
.Wait();
Stream stream = null;
Task.Factory
.StartNew(() => stream = parts.First().ReadAsStreamAsync().Result,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default)
.Wait();
return stream;
}
这张贴有 ENCTYPE =的multipart / form-data的
的HTTP表单时为我工作。
This works for me when posting an HTTP form with enctype="multipart/form-data"
.
这篇关于如何zip文件发送到ASP.NET的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!