c# – 使用HTTP GET流式传输文件:ASP .NET CORE API
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用HTTP GET流式传输文件:ASP .NET CORE API,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1794字,纯文字阅读大概需要3分钟。
内容图文
![c# – 使用HTTP GET流式传输文件:ASP .NET CORE API](/upload/InfoBanner/zyjiaocheng/820/a49bd7a0083f4568bd3bfdae64e2f1f2.jpg)
我已经编写了一个控制器来下载/流文件到客户端本地机器.除了只生成响应体之外,代码不会在对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全部内容,希望文章能够帮你解决c# – 使用HTTP GET流式传输文件:ASP .NET CORE API所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。