本文介绍了在ASP.Net Core Web API中返回文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ASP.Net Web API控制器中返回文件,但是我所有的方法都返回 HttpResponseMessage 作为JSON。

I want to return a file in my ASP.Net Web API Controller, but all my approaches return the HttpResponseMessage as 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 Content Header设置为 application / json

When I call this endpoint in my browser, the Web API returns the HttpResponseMessage as JSON with the HTTP Content Header set to application/json.

推荐答案

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

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

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

这篇关于在ASP.Net Core Web API中返回文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:22