Почему браузер не скачивает файл, который передает Web Api?

Имеется Web Api сделанный на .net core 2.1. В нем есть действие - скачивание файла. Код действия:

[HttpGet("download/{id}")]
public HttpResponseMessage DownloadDocumentFile(int id)
        {
            logger.Info(BuildInfoMessage(nameof(DownloadDocumentFile), $"{nameof(id)} = {id}"));

            var message = new HttpResponseMessage(HttpStatusCode.OK);
            
            try
            {
                var file = documents.GetDownloadableFile(id);

                message.Content = new ByteArrayContent(file.DocumentData);
                message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{file.DocumentName}.zip"
                };
                message.Content.Headers.ContentLength = file.DocumentData.LongLength;
                message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

            }
            catch (Exception ex)
            {
                logger.Error(BuildErrorMessage(nameof(DownloadDocumentFile), ex, $"{nameof(id)} = {id}"));

                message.Content = null;
                message.StatusCode = HttpStatusCode.InternalServerError;
            }

            return message;
        }

Но при обращении к этому действию из браузера идет ответ в виде json-строки:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=TestDocument43.zip"]},{"key":"Content-Length","value":["796683"]},{"key":"Content-Type","value":["application/zip"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

, а сам файл не скачивается. Искал в интернете ответы на этот вопрос, вроде все сделано так, как пишут люди, но результат не совпадает.


Ответы (1 шт):

Автор решения: Exploding Kitten

Попробуйте воспользоваться методом File из ControllerBase:

[HttpGet("download/{id}")]
public IActionResult DownloadDocumentFile(int id)
{
    // ... логи, обработка исключений ...
    var file = documents.GetDownloadableFile(id);

    return File(file.DocumentData, "application/zip");
}
→ Ссылка