Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net MVC中Webapi控制器中的HttpResponse_Asp.net_Asp.net Mvc 3_Wcf_Rest_Asp.net Web Api - Fatal编程技术网

Asp.net MVC中Webapi控制器中的HttpResponse

Asp.net MVC中Webapi控制器中的HttpResponse,asp.net,asp.net-mvc-3,wcf,rest,asp.net-web-api,Asp.net,Asp.net Mvc 3,Wcf,Rest,Asp.net Web Api,我使用的Web api控制器如下所示: [HttpPost] public HttpResponseMessage PostMethod(string filename) { Stream downloadStream = BL.method(fileName); HttpResponseMessage response = new HttpResponseMessage(); response.content= new StreamCon

我使用的Web api控制器如下所示:

[HttpPost]    
public HttpResponseMessage PostMethod(string filename)    
{
    Stream downloadStream = BL.method(fileName);    
    HttpResponseMessage response = new HttpResponseMessage();    
    response.content= new StreamContent(downloadStream);    
    return response;    
}
当我尝试使用fiddler调用上述方法时,我得到一个异常,即

“downloadStream.ReadTimeout”引发了类型为的异常 “System.InvalidOperationException”


流是否可以设置为响应并发送?上述代码是否有任何修改?

您的流似乎有问题。如果不知道流是如何生成的,很难说。如果替换
BL.method(文件名)FileStream
自己加载文件应该可以(我自己刚刚测试过)

另一方面,您的方法存在一些问题:

  • 你用邮局。因为你没有改变任何事情,所以你会变得更好
  • 您没有设置
    ContentType
    标题,因此客户端可能在使用资源时遇到问题
  • 您没有处理该流,因此该流可能处于边缘,通常不好

  • 尝试使用PushStreamContent,可能通过不在内存中缓冲文件,可以避免超时

        [HttpPost]
        public HttpResponseMessage PostMethod(string filename)
        {
            Stream downloadStream = BL.method(fileName);
            HttpResponseMessage response = new HttpResponseMessage();
            response.Content = new PushStreamContent((responseStream, httpContent, tc) => {
                                                         downloadStream.CopyTo(responseStream);
                                                         responseStream.Close();
                                                     }, "application/octet-stream");
    
            return response;
        }
    

    实际上我不能替换BL.method(文件名);使用filestream,因为我正在从数据库流式传输此文件。我正在通过提供其文件名从数据库获取流。因此,有什么解决方案吗?似乎存在缺陷,而不是在Web API中。