7

我正在尝试使用 Web API 服务。我正在尝试通过 GET 请求进行文件下载。该方法触发得很好并达到了我的断点。我创建一个响应并返回它。然后,奇怪的是,断点再次被击中。我正在使用 Firefox 插件海报来测试它。海报说服务器没有响应。知道为什么会这样吗?

这是响应创建代码:

HttpResponseMessage result = this.Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = file.Length;
result.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(-1));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("Attachment") { FileName = file.Name };
return result;

唯一的重大变化(我能想到的)是我的 WebApiConfig 如下所示:

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });

我的方法签名如下所示: public HttpResponseMessage GetUpdate(int Id)

我所有的其他动作都很好。我是否错过了客户端的某些内容,例如接受标头或其他内容?我现在只是在做一个简单的 GET。

谢谢!

4

1 回答 1

6

找到了!using 语句似乎是个麻烦。在发送结果之前,流可能已被处理掉。我像这样更新了我的代码,它开始工作:

var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
result.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(-1));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("Attachment") { FileName = Path.GetFileName(filePath) };
于 2013-06-05T21:35:03.770 回答