Asp.net Web Api流 [英] Asp.net Web Api Streaming

查看:68
本文介绍了Asp.net Web Api流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将文件流式传输到我的Web服务.在我的Controller(ApiController)中,我具有一个Post函数,如下所示:

I have been trying to stream a file to my web service. In my Controller(ApiController) I have a Post function as follows:

public void Post(Stream stream)
{
    if (stream != null && stream.Length > 0)
    {
        _websitesContext.Files.Add(new DbFile() { Filename = Guid.NewGuid().ToString(), FileBytes= ToBytes(stream) });
        _websitesContext.SaveChanges();
    }
}

我一直在尝试通过以下操作与Web客户端流式传输文件:

I have been trying to stream a file with my web client by doing the following:

public void UploadFileStream(HttpPostedFileBase file)
{
    WebClient myWebClient = new WebClient();
    Stream postStream = myWebClient.OpenWrite(GetFileServiceUrl(), "POST");
    var buffer = ToBytes(file.InputStream);
    postStream.Write(buffer, 0,buffer.Length);
    postStream.Close();
}

现在,当我调试Web服务时,它进入了Post函数,但流始终为null.想知道是否有人知道为什么会这样吗?

Now when i debug my web service, it gets into the Post function, but stream is always null. Was wondering if anyone may have an idea why this is happening?

推荐答案

Web API未将模型绑定到"Stream"类型,因此您会看到此行为.您可以通过执行以下操作来捕获传入的请求流:Request.Content.ReadAsStreamAsync()

Web API doesn't model bind to 'Stream' type hence you are seeing the behavior. You could instead capture the incoming request stream by doing: Request.Content.ReadAsStreamAsync()

示例:

public async Task<HttpResponseMessage> UploadFile(HttpRequestMessage request)
    {
        Stream requestStream = await request.Content.ReadAsStreamAsync();

注意:您甚至不需要HttpRequestMessage作为参数,因为您始终可以通过ApiController的"Request"属性访问此请求消息.

Note: you need not even have HttpRequestMessage as a parameter as you could always access this request message via the "Request" property available via ApiController.

这篇关于Asp.net Web Api流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆