Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# - How to send zip files to ASP.NET WebApi

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...