从HttpResponseMessage获取Excel文件

时间:2017-07-12 16:09:26

标签: c# asp.net excel asp.net-core

我正在开发一个ASP.NET Core 2.2项目,我需要使用我的浏览器下载我的Excel,但是当我正在执行我的请求时,我只是得到了一些Json。

我的Excel在流中,流不是空的!

这是我的代码:

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
            var streamContent = new StreamContent(stream);

            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            streamContent.Headers.ContentDisposition.FileName = "Excel.xlsx";

            message.Content = streamContent;

            return message;

以下是我得到的回复:

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]},{"key":"Content-Disposition","value":["attachment; filename=Excel.xlsx"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

那么,有人知道如何使用HttpResponseMessage发送我的Excel文件吗?

我可以使用Filesteam下载我的excel文件,但我不想使用这种方式,因为我无法获取任何Http错误消息(错误请求,内部等) 但如果有人知道如何发送这样的信息并返回文件流,我将很高兴看到您的建议!

编辑:这是我返回FileStreamResult

时的代码
                return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

2 个答案:

答案 0 :(得分:1)

您可以从Stream读取Byte数组,并返回FileContentResult。

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public async Task<ActionResult> Get(string fileName)
        {
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline")
            {
                FileName = "Excel.xlsx"
            };
            Response.Headers.Add("Content-Disposition", cd.ToString());
            StreamContent stream = YOUR_STREAM_SOURCE
            byte[] content = await stream.ReadAsByteArrayAsync();
            return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
}

答案 1 :(得分:0)

    async Task<bool> DownloadDocument(string authorizationToken, string fileName)
    {
        try
        {
            string url = "yoururl":
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
                HttpResponseMessage response = await httpClient.GetAsync(url);
                await ReadAsFileAsync(response.Content, fileName, true);
                return true;
            }

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            return false;
        }