Asp.net WebAPI 使用流下载文件注意事项
public HttpResponseMessage Post(string version, string environment, string filetype) { var path = @"C:\Temp\test.exe"; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open, FileAccess.Read); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; }
注意事项
- 不用调用stream.Dispose() 方法去释放资源,WebAPI会将数据发送给客户端后自动调用Dispose 方法,因此不可以使用 using (var stream = …) 代码块,这样会报500
- 必须确保流的起始位置为 0,
stream.Seek(0, SeekOrigin.Begin);
或stream.Position = 0;