gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:48:38 24 4
gpt4 key购买 nike

我已经编写了一个 Controller 来将文件下载/流式传输到客户端本地机器。除了仅生成响应正文之外,代码不会在对 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}

最佳答案

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

引用File Streaming in ASP.NET Core的答案

关于c# - 使用 HTTP GET : ASP . NET CORE API 流式传输文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44643626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com