一尘不染

如何将zip文件发送到ASP.NET WebApi

json

我想知道如何将zip文件发送到WebApi控制器,反之亦然。问题是我的WebApi使用json传输数据。一个zip文件不可序列化,或者是流。字符串将可序列化。但是除了将zip转换为字符串并发送字符串之外,还必须有其他解决方案。这听起来是错误的。

任何想法如何做到这一点?


阅读 221

收藏
2020-07-27

共1个答案

一尘不染

如果您的API方法期望使用,HttpRequestMessage则可以从中提取流:

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

当使用张贴HTTP表单时,这对我有用enctype="multipart/form-data"

2020-07-27