首页 / ASP.NET Core / 正文

[ASP.NET Core Web API]在ASP.NET Core Web API中如何返回下载文件?

5182 发布于: 2018-09-12 读完约需6分钟

问题描述

在ASP.NET Web API的应用程序中,如果我们需要控制器返回下载文件,可以使用HttpResponseMessage类型,比如:

[HttpGet]
[Authorize]
[Route("OpenFile/{QRFileId}")]
public HttpResponseMessage OpenFile(int QRFileId)
{
    QRFileRepository _repo = new QRFileRepository();
    var QRFile = _repo.GetQRFileById(QRFileId);
    if (QRFile == null)
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    string path = ConfigurationManager.AppSettings["QRFolder"] + + QRFile.QRId + @"\" + QRFile.FileName;
    if (!File.Exists(path))
        return new HttpResponseMessage(HttpStatusCode.BadRequest);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    //response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    Byte[] bytes = File.ReadAllBytes(path);
    //String file = Convert.ToBase64String(bytes);
    response.Content = new ByteArrayContent(bytes);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    response.Content.Headers.ContentDisposition.FileName = QRFile.FileName;

    return response;
}

但在ASP.NET Core Web API 的控制器中,没有了HttpResponseMessage这个类型了。

那么,在ASP.NET Core Web API中如何返回下载文件呢?

方案一

由于在ASP.NET Core 程序应用开发中,控制器使用的是混合的API基类,即:MVC,Razor Pages以及ASP.NET Core Web API均使用的同一个控制器基类,所以,所有的操作(Action)都是IActionResult,而没有了HttpResponseMessage这种返回类型。
因此,ASP.NET Core Web API下载文件的控制器与以前的ASP.NET Web API是不太一样,具体实现可以如下:

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;

        if(stream == null)
            return NotFound();

        return File(memory, "application/octet-stream"); // 返回一个文件流
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [ASP.NET Core]在ASP.NET Core跨平台应用程序开发中如何返回带有Http状态码的JSON数据?

下一篇: [ASP.NET Core Razor Pages系列教程]ASP.NET Core Razor Pages 简介(00)

本文永久链接码友网 » [ASP.NET Core Web API]在ASP.NET Core Web API中如何返回下载文件?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册