【问题标题】:HttpResponse in Webapi controller in MVCMVC 中 Webapi 控制器中的 HttpResponse
【发布时间】:2012-10-13 11:19:39
【问题描述】:

我正在使用 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'。

可以设置流作为响应并发送吗?上面的代码有修改吗?

【问题讨论】:

    标签: asp.net asp.net-mvc-3 wcf rest asp.net-web-api


    【解决方案1】:

    您的信息流似乎有问题。不知道流是如何产生的,很难说。如果您将 BL.method(fileName); 替换为使用 FileStream 自己加载文件,这应该可以工作(我刚刚自己测试过)。

    在旁注中,您的方法存在一些问题:

    1. 您使用 POST。由于您没有更改任何内容,因此 GET 更好。
    2. 您没有设置 ContentType 标头,因此客户端在使用资源时可能会遇到问题
    3. 您没有处理流,因此该流可能会处于不稳定状态并且通常不好。

    【讨论】:

    • 其实我无法替换 BL.method(fileName);使用文件流,因为我正在从数据库中流式传输此文件仪式。我通过提供其文件名从 db 中获取流。那么有什么解决方案吗?
    • Web API 中似乎没有错误。
    【解决方案2】:

    尝试使用 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;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多