S
S
Stazhor2020-09-10 13:24:37
ASP.NET
Stazhor, 2020-09-10 13:24:37

Why doesn't the browser download the file that the Web Api passes?

There is Web Api made on .net core 2.1. It has an action - downloading a file. Action code:

[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;
        }


But when accessing this action from the browser, the response is in the form of a json string:
{"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}
but the file is not downloading. I searched the Internet for answers to this question, everything seems to be done the way people write, but the result does not match.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2020-09-10
@cicatrix

You return HttpResponseMessage, but you need to return FileContentResult

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question