c# - WebAPI 返回损坏的、不完整的文件

标签 c# asp.net-web-api2 httpresponsemessage

我想从 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");
    }
}

很遗憾,下载的文件不完整。使用 Android 应用程序时的消息是:

java.io.EOFException: source exhausted prematurely

最佳答案

问题很可能是您的 Android 客户端认为下载已经结束,但实际上尚未结束。
要轻松解决此问题,您可以改用此方法,它会立即返回整个文件(而不是流式传输):

result.Content = new ByteArrayContent(File.ReadAllBytes(path));

关于c# - WebAPI 返回损坏的、不完整的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44925841/

相关文章:

.NET Framework MVC 和 Web Api Auth JWT

.net - HttpClient.ReadAsAsync<T> 在使用 [Serializable] 时返回空对象

c# - 从另一个应用程序中的 HttpRequestException 获取值

c# - 如何限制从 Roslyn 脚本引擎访问程序集中的成员?

c# - 中间件使用从客户端发送的参数,并根据这些参数允许或不允许与端点交互

c# - 为什么 FileSystemWatcher 检测不到来自 Visual Studio 的更改?

asp.net-mvc-5 - 如何在 MVC 5 Web 应用程序和 Web API 2 应用程序之间共享访问 token

asp.net-web-api - 无法从 Web API 下载 csv 文件

c# - 使用 CSVHelper 从 HttpResponseMessage 解析 CSV

c# - kendoui网格全选