【问题标题】:Streaming files using HTTP GET : ASP .NET CORE API使用 HTTP GET 流式传输文件:ASP .NET CORE API
【发布时间】:2017-11-22 10:35:00
【问题描述】:

我已经编写了一个控制器来将文件下载/流式传输到客户端本地计算机。该代码不会在对 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;
            }
        }
        }
    }

回复:

{"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}

【问题讨论】:

标签: c# asp.net .net


【解决方案1】:

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

参考File Streaming in ASP.NET Core的答案

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 2010-10-12
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多