c# - ASP.Net Core Web API 中的返回文件

标签 c# asp.net-core .net-core asp.net-core-webapi

问题

我想在我的 ASP.Net Web API Controller 中返回一个文件,但我所有的方法都将 HttpResponseMessage 作为 JSON 返回。

到目前为止的代码

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;
}

当我在浏览器中调用此端点时,Web API 返回 HttpResponseMessage 作为 JSON,并将 HTTP 内容 header 设置为 application/json

最佳答案

如果这是 ASP.net-Core,那么您正在混合 Web API 版本。让操作返回派生的 IActionResult,因为在您当前的代码中,框架将 HttpResponseMessage 视为模型。

[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
    }    
}

注意:

The framework will dispose of the stream used in this case when the response is completed. If a using statement is used, the stream will be disposed before the response has been sent and result in an exception or corrupt response.

关于c# - ASP.Net Core Web API 中的返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460198/

相关文章:

c# - 日志记录逻辑应该位于 DDD 解决方案中的什么位置?

c# - 默认字体大小列表

model-view-controller - ErroCS1929 'IHtmlHelper<IPagedList<Book>>' 不包含 'PagedListPager' 的定义

visual-studio - Docker AspNet Core + Couchbase

c# - 在 Linux 上查看 dotnetcore 2 自包含应用程序的内存使用情况统计信息

c# - ASP.NET 异步和等待

c# - 我如何转换int?进入整数

c# - 如何在 .NET Core 的 Startup 类构造函数中访问 AppSettings

twitter-bootstrap - 在 .Net Core Angular 模板中使用 webpack 编译 bootstrap scss

c# - 如何上传附件到服务器,Net Core+React(Redux)