将没有缓冲区的数据从MultipartMemoryStreamProvider传输到输出流

时间:2015-04-20 14:29:21

标签: c# asp.net asp.net-web-api upload proxy

我正在做一种代理。客户端将文件上载到Web API方法,此Web API方法将文件发送到其他HTTP位置。我有这段代码:

[HttpPost]
public async Task mPost(string id)
{     
    var provider = new MultipartMemoryStreamProvider();
    var r = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(async t =>
    {
        var file = provider.Contents.First();                
        var buffer = await file.ReadAsByteArrayAsync();
        var stream = new MemoryStream(buffer);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.ExpectContinue = false;

            using (var content = new StreamContent(stream))
            {                       
                using (var req = new HttpRequestMessage(HttpMethod.Put, "target_url"))
                {        
                    req.Content = content;

                    using (HttpResponseMessage resp = client.SendAsync(req).Result)
                    {
                        resp.EnsureSuccessStatusCode();
                    }
                }
            }
        }

    });

它有效,但我不喜欢的是在某些时候(var buffer = await file.ReadAsByteArrayAsync();)我在服务器的内存中拥有所有文件数据。

如何将数据直接从输入流传输到输出而不将其保留在内存缓冲区中?

1 个答案:

答案 0 :(得分:-1)

一种选择是使用WebRequest代替HttpClient,并直接将file流复制到请求中。

要异步请求流,请使用WebRequest.GetRequestStreamAsync并发送内容 - HttpContent.CopyToAsync

有许多样本以这种方式表达POST - 即WebRequest.GetRequestStreamAsync() method timesout each time for MNS access token