How to send zip files to ASP.NET WebApi

后端 未结 2 1254
死守一世寂寞
死守一世寂寞 2020-12-15 01:17

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, eit

2条回答
  •  忘掉有多难
    2020-12-15 01:43

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

    This works for me when posting an HTTP form with enctype="multipart/form-data".

提交回复
热议问题