【发布时间】:2017-07-05 12:07:09
【问题描述】:
我想从 WebApi 端点返回一个图像。这是我的方法:
[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");
}
}
很遗憾,下载的文件不完整。消费安卓应用的消息是:
java.io.EOFException: 源过早耗尽
【问题讨论】:
-
在标题中添加
content-length怎么样?result.Content.Headers.Add(@"Content-Length", content.Length.ToString()); -
那是因为
StreamContent不包含Length的定义 -
正确,但尝试添加标题。
-
尝试添加标题并且它已经被设置为正确的值。这闻起来像 StreamContent 类中的错误,或者它在某个地方被使用。
标签: c# asp.net-web-api2 httpresponsemessage