使用HTTP GET流式传输文件:ASP .NET CORE API

4 .net c# asp.net

我已经编写了一个控制器来下载/流文件到客户端本地机器.除了只生成响应体之外,代码不会在对URL进行GET时传输文件.

streamcontent方法有什么问题.在调试我找不到问题.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;

namespace FileDownloaderService.Controllers
{
    [Route("api/[controller]")]
    public class FileDownloadController : Controller
    {

        [HttpGet]
        public HttpResponseMessage Get() {
            string filename = "ASPNETCore" + ".pdf";
            string path = @"C:\Users\INPYADAV\Documents\LearningMaterial\"+ filename;

            if (System.IO.File.Exists(path)) {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new FileStream(path, FileMode.Open);
                stream.Position = 0;
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition.FileName = filename;
                return result;
            }
            else
            {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
                return result;
            }
        }
        }
    }
Run Code Online (Sandbox Code Playgroud)

响应:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=ASPNETCore.pdf"]},{"key":"Content-Type","value":["application/pdf"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
Run Code Online (Sandbox Code Playgroud)

Pra*_*mar 6

在ASP.NET Core中,如果要发送自定义响应,则需要使用IActionResult.所有其他响应将被序列化(默认为JSON)并作为响应正文发送.

请参阅ASP.NET Core中的文件流处理中的答案