我想在 ASP.Net Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为
HttpResponseMessage
,参考代码如下:
public async Task<HttpResponseMessage> DownloadAsync(string id)
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent({
{__insert_stream_here__}});
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
当我在浏览器测试时,我发现Api将 HttpResponseMessage 作为 json格式返回,同时 Http Header 头为
application/json
,请问我该如何正确配置成文件流返回。
我觉得大概有两种做法:
-
返回 FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
var fileName="myfileName.txt";
var mimeType="application/....";
Stream stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
FileDownloadName = fileName
-
返回 FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
var fileName="myfileName.txt";
var mimeType="application/....";
byte[] fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
FileDownloadName = fileName
这是因为你的代码将 HttpResponseMessage 视为一个 Model,如果你的代码是 Asp.NET Core 的话,其实你可以混入一些其他特性,比如将你的 Action 返回值设置为一个派生自 IActionResult 下的某一个子类,参考如下代码:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}")]
public async Task<IActionResult> Download(string id) {
Stream stream = await {
{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/octet-stream"); // returns a FileStreamResult
记得我在 webapi 中实现类似功能时,我用的就是后面这位大佬提供的方式,
ActionResult + File
的方式,简单粗暴。
咨询区 Jan Kruse:我想在 ASP.Net Web API 中返回 File 文件,我目前的做法是将 Action 返回值设为 HttpResponseMessage,参考代码如下...
namespace DocOnlineView.UI.Controllers.MVC
API
public class HomeController :
Api
Controller
[
Http
Get]
public DataTable CourseViewOnLine(string
file
Name)
DataTable dtlist = new DataTable();
dtlist.Columns.Add("TempDoc
Html
", typeof(string));
string
file
Dire = "/
File
s";
string sourceDoc = Path.Combine(
file
Dire,
file
Name);
string saveDoc = "";
string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
bool result = false;
if (docExtendName == ".pdf")
//pdf模板文件
string temp
File
= Path.Combine(
file
Dire, "temppdf.
html
");
saveDoc = Path.Combine(
file
Dire, "view
File
s/onlinepdf.
html
");
result = PdfTo
Html
(
sourceDoc,
System.
Web
.
Http
Context.Current.Server.MapPath(temp
File
),
System.
Web
.
Http
Context.Current.Server.MapPath(saveDoc));
saveDoc = Path.Combine(
file
Dire, "view
File
s/onlineview.
html
");
result = OfficeDocumentTo
Html
(
System.
Web
.
Http
Context.Current.Server.MapPath(sourceDoc),
System.
Web
.
Http
Context.Current.Server.MapPath(saveDoc));
如果我想在
ASP.Net
Web
API
中
返回
File
文件,我目前的做法是将 Action
返回
值设为
Http
ResponseMessage,参考代码如下:
publicasyncTask<
Http
ResponseMessage>DownloadAsync(stringid)
varresponse=new
Http
ResponseMessage(
Http
StatusCode.OK);
response.Content=newStreamCo...
http
s://stackoverflow.com/questions/42460198/return-
file
-in-asp-net-
core
-
web
-
api
1: Return
File
StreamResult
[
Http
Get("get-
file
-stream/{id}"]
public async Task<
File
StreamResult> DownloadAsync(string id)
var
file
Name="my
file
Name.txt";
var mim
随意,如果您有任何问题或要求更多的解释或样品。 我也接受拉取请求!
:sparkling_heart: 如果该存储库对您有所帮助-如果您加入我的官方支持者小组,我将非常高兴:
:backhand_index_pointing_right:
设置.NET
Core
的工作环境
安装 , , 或您其他喜欢的.NET IDE
创建新的
Web
Api
项目
我们将为
Web
Api
项目使用默认的Visual Studio模板:
从Visual Studio菜单中选择:
File
=> New => Project
从Templates => Visual C# => .Net
Core
一个
ASP.NET
Co
Heroku中的Dockerized
ASP.NET
Core
3
Web
API
应用程序
在此博客文章中,我们将创建一个容器化的
ASP.NET
Core
3.1
Web
API
项目,并使用GitHub Actions建立CI / CD管道。 在GitHub工作流程中,我们将构建和测试
Web
API
项目,并将最终的docker映像部署到Heroku。
本文旨在将一些补充信息添加到Microsoft Docs中的正式文档中。 我的目标是将代码/注释和Swagger UI元素之间的点连接起来。
在本文中,我们将介绍有关上载单个文件,上载文件列表以及在FormData对象中上载文件的示例。
publicasyncTask<
Http
ResponseMessage>DownloadAsync(stringid)
varresponse=new
Http
ResponseMessage(
Http
StatusCode.OK);
response.Content=ne...
[
Http
Post]
[Route("Post
File
")]
public String Post
File
([FromForm] IFormCollection formCollection)
String result = "Fail";
if (formCollection.Con
当浏览器在请求资源时,会通过
http
返回
头中的content-type决定如何显示/处理将要加载的数据,如果这个类型浏览器能够支持阅览,浏览器就会直接展示该资源,比如png、jpeg、video等格式。在某些下载文件的场景中,服务端可能会
返回
文件流,并在
返回
头中带上Content-Type:application/octet-stream,告知浏览器这是一个字节流,浏览器处理字节流的默认方式就是下载。
Application/octet-stream是应用程序文件的默认值。意思是未知的应用程序文件,浏览器一
//前端请求预览或下载文件(微信小程序也一样)
[
Http
Get]
public async Task<IActionResult> DownloadYFPreview([FromQuery] string openId, string dbName, string orderName, string id)
if (openId == null || dbName == null || orderName == n
你要明白,任何问题都不是孤立存在的,一定有人曾经遇到过,并且已经有更好的解决办法了,只是我还不知道。我不应该在黑暗中独自前行,去重新发明轮子,也许我的顿悟,只是别人的基本功!我应该要站在巨人的肩膀上,学习更成熟的经验和方法,然后再来解决这个问题
02-21
使用起来也很简单,我们构造 ExcelHelper 类,并在controller里面使用。
比如 person类有 id,name,age 3个属性,则 在controller里面这样调用
[Route("ExportExcel")]
[
Http
Get]
public IActionRes...
Asp.Net
Core
专案练习集
此为在对
ASP.NET
Core
进行学习时的测试专案,注解都有简易的说明。如果您对内容有疑惑时,那么把专案执行起来,使用或了解测试的结果,将有助于学习。其中少数范例,使浏览器会是比较好的选择。
请给一颗星星! :star:
如果您喜欢或使用此专案进行学习,请给它一颗星星,谢谢。我会长期维护此专案,也建议加入手表。
专案自述文件
我提供的范例已经被AspNet
Core
.Docs团队接受与合并,请直接到AspNet
Core
.Docs Repos取得。
This essential classic title provides a comprehensive foundation in the C# programming language and the frameworks it lives in. Now in its 8th edition, you’ll find all the very latest C# 7.1 and .NET 4.7 features here, along with four brand new chapters on Microsoft’s lightweight, cross-platform framework, .NET
Core
, up to and including .NET
Core
2.0. Coverage of
ASP.NET
Core
, Entity Framework (EF)
Core
, and more, sits alongside the latest updates to .NET, including Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), and
ASP.NET
MVC.
Dive in and discover why Pro C# has been a favorite of C# developers worldwide for over 15 years. Gain a solid foundation in object-oriented development techniques, attributes and reflection, generics and collections as well as numerous advanced topics not found in other texts (such as CIL opcodes and emitting dynamic assemblies). With the help of this book you’ll have the confidence to put C# into practice and explore the .NET universe on your own terms.
What You Will Learn
Discover the latest C# 7.1 features, from tuples to pattern matching
Hit the ground running with Microsoft’s lightweight, open source .NET
Core
platform, including
ASP.NET
Core
MVC,
ASP.NET
Core
web
services, and Entity Framework
Core
Find complete coverage of XAML, .NET 4.7 and Visual Studio 2017
Understand the philosophy behind .NET and the new, cross-platform alternative, .NET
Core
Table of Contents
Part I: Introducing C# and the .NET Platform
Chapter 1: The Philosophy of .NET
Chapter 2: Building C# Applications
Part II:
Core
C# Programing
Chapter 3:
Core
C# Programming Constructs, Part I
Chapter 4:
Core
C# Programming Constructs, Part II
Part III: Object-Oriented Programming with C#
Chapter 5: Understanding Encapsulation
Chapter 6: Understanding Inheritance and Polymorphism
Chapter 7: Understanding Structured Exception Handling
Chapter 8: Working with Interfaces
Part IV: Advanced C# Programming
Chapter 9: Collections and Generics
以
ASP.NET
Core
Web
API
作后端
API
,用 Vue 构建前端页面,用 Axios 从前端访问后端
API
,包括文件的上传和下载。
准备文件上传的
API
#region 文件上传 可以带参数
[
Http
Post(upload)]
public
Js
onResult uploadProject(IForm
File
file
, string userId)
if (
file
!= null)
var
file
Dir = D:\\aaa;
if (!Directory.Exists(
file
Dir))
下载文件到本地是很多项目开发中需要实现的一个很简单的功能。说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是
ASP.NET
Web
Api
方式
返回
Http
ResponseMessage下载文件到本地。实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为
返回
的
Http
ResponseMessage的Content。直接贴出DownloadController控件器的代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
本来是已经压缩过了,不过第一反应应该是用户下的数量多,导致压缩包很大,然后自己测试发现,只是等待的时间比较久而已,仍然是下载状态中,并不是系统慢,但是用户体验肯定是最直观的,确实是我们做得不够好,单纯弹出遮罩层显示冰冷的“拼命加载中……”,对用户来说确实不够友好。嗯,了解实际情况了,那就开撸,增加用户体验。
经过简单的调研,得到以下结论。
ASP.NET
CORE
提供
File
Result这种类型的ActionResult,可以直接
返回
文件结果,不需要直接处理
Http
Response。
通过Stream可以直接
返回
...
<h3>回答1:</h3><br/>
ASP.NET
Core
Web
API
是一种用于构建
Web
API
的框架。它是微软开发的一个开源框架,旨在提供高性能、可扩展性和可靠性,支持跨平台开发,并且易于使用。
ASP.NET
Core
Web
API
基于 .NET
Core
平台,可以运行在 Windows、Linux 和 macOS 等多个操作系统上。它支持使用 C# 或者其他 .NET 支持的语言进行开发,并且提供了许多开箱即用的功能,如模型绑定、身份验证、授权、路由等等。
使用
ASP.NET
Core
Web
API
,你可以构建 RESTful
API
,支持多种数据格式,如
JS
ON、XML 等等。你还可以轻松地集成其他框架和工具,如 Swagger、Entity Framework
Core
、SignalR 等等。
总之,
ASP.NET
Core
Web
API
是一个功能强大、灵活、易于使用的框架,非常适合构建
Web
API
。
<h3>回答2:</h3><br/>
ASP.NET
Core
Web
API
是微软推出的一种服务器端的轻量级框架,用于构建基于 RESTful 的
Web
API
。该框架建立在 .NET
Core
上,并具有很好的可扩展性和灵活性,可适用于跨平台开发。
ASP.NET
Core
Web
API
的主要特点包括:
1. 开箱即用的依赖注入:该框架提供了一个内置的依赖注入容器,使得 DI 可以轻松地集成到
Web
API
的开发中。
2. 轻量级:由于底层是使用 .NET
Core
构建的,因此
ASP.NET
Core
Web
API
框架非常灵活、快速、轻量级,并且能够满足高并发访问的需求。
3. 跨平台支持:
ASP.NET
Core
Web
API
是跨平台的,可以运行在 Windows、Linux 和 macOS 等操作系统上。
4. 开放式标准:该框架遵循开放式的标准,并支持多种数据格式、服务器框架和插件。
5. 网络安全:
ASP.NET
Core
Web
API
提供了多种安全功能,包括认证、授权和加密等,以保护
Web
应用程序免受网络攻击。
总之,
ASP.NET
Core
Web
API
框架是一个方便、快捷、灵活和高性能的框架,适用于构建任何规模的
Web
API
应用程序。与此同时,该框架还提供了良好的文档和社区支持,愿意学习的开发者可以通过微软的官方文档和各种社区论坛,快速上手并掌握该框架的使用。
<h3>回答3:</h3><br/>
ASP.NET
Core
Web
API
是一个开放源代码跨平台的
Web
框架,用于开发基于
HTTP
协议的RESTful服务,并支持各种客户端,包括
Web
界面及流行语言开发的客户端应用程序。其已经成为目前.NET生态系统中最重要的发展方向之一。
相比于传统的.NET框架,
ASP.NET
Core
Web
API
具有以下几个优点:
1. 跨平台:在Linux、Mac、Windows等平台上都可以运行,且不必担心所使用的系统版本问题;
2. 高性能:
ASP.NET
Core
Web
API
在响应请求方面有极佳的性能,对于高并发访问的场景有着不错的表现;
3. 轻量级:
ASP.NET
Core
Web
API
具有比传统的.NET框架更轻量级的特点,其运行时占用的硬盘空间和内存资源更少;
4. 便于部署:用Docker等虚拟化容器将应用打包后部署非常简单,不需要过多的配置,适用于现代化的云端应用场景。
在开发方面,
ASP.NET
Core
Web
API
提供了丰富的工具和库,使
Web
API
的开发效率更高,且可用于多种类型的
Web
应用程序,例如单页应用程序、移动客户端、大型企业软件等。通过使用
ASP.NET
Core
Web
API
,开发人员可以轻松创建高效稳定的
Web
服务和RESTful
API
s。
总之,
ASP.NET
Core
Web
API
是一个反应迅速、易于扩展的开发框架,不仅能够加速
Web
应用程序的开发工作,更能够提供高性能的
Web
服务,从而大大提升用户体验。