本文介绍了WebAPI返回损坏的不完整文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从WebApi端点返回图像.这是我的方法:
I want to return an image from WebApi endpoint. This is my method:
[System.Web.Http.HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
string dirPath = HttpContext.Current.Server.MapPath(Constants.ATTACHMENT_FOLDER);
string path = string.Format($"{dirPath}\\{id}.jpg");
try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
var content = new StreamContent(stream);
result.Content = content;
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(path) };
return result;
}
catch (FileNotFoundException ex)
{
_log.Warn($"Image {path} was not found on the server.");
return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid image ID");
}
}
很遗憾,下载的文件不完整.正在使用Android应用程序的消息为:
Unfortunately, the file that is downloaded is incomplete. The message in consuming Android app is:
推荐答案
原来,这是由压缩引起的,压缩是为此控制器中的所有响应设置的.在控制器的构造函数中设置了GZip编码:
Turns out that this was caused by compression, that was set for all responses in this controller. There is GZip encoding set up in controller's constructor:
HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
HttpContext.Current.Response.Filter = new GZipStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);
为了解决这个问题,我将这些行添加到了我的方法中(就在 try
块开始之后):
To solve this, I added these lines to my method(just after beginning of try
block):
// reset encoding and GZip filter
HttpContext.Current.Response.Headers["Content-Encoding"] = "";
HttpContext.Current.Response.Headers["Content-Type"] = "";
// later content type is set to image/jpeg, and default is application/json
HttpContext.Current.Response.Filter = null;
此外,我正在设置内容类型和长度,如下所示:
Also, I'm setting content type and length like this:
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = stream.Length;
这篇关于WebAPI返回损坏的不完整文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!