【问题标题】:AspNetCore download (export) file [duplicate]AspNetCore 下载(导出)文件 [重复]
【发布时间】:2018-01-27 23:45:32
【问题描述】:

在我的 .Net Framework 4.5 项目之一中,我一直在创建响应 (file download),如下所示

.Net Framework 4.5 版本

public virtual HttpResponseMessage ExportExcel()
{
    ...................
    ....................
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    Stream stream = new MemoryStream(bytes);
    response.Content = new StreamContent(stream);
    var cookie = new CookieHeaderValue("customValue", "true");
    cookie.Path = "/";
    response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = ExportFileName
    };
    return response;.
}

如您所见,我正在添加 cookie、Header ContentType 等。

这是我移植的 .Net Core 版本。

public virtual ActionResult ExportExcel()
{
    ........
    .......
    byte[] bytes = _svc.Export(excelTemplatePath, ExcelColumns);
    Response.StatusCode = 200;
    Response.Cookies.Append("customValue", "true");
    Response.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").ToString();        
    return File(bytes, "application/x-msdownload", "");
    }
}

问题:

1- 我找不到设置ContentDisposition的方法

2- 没有Response.Content(我找不到 Response.Content = .Net Core 中的新 StreamContent(stream)。

【问题讨论】:

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


    【解决方案1】:

    我用这种方式,不用关心ContentDisposition:

    public IActionResult ExportExcel()
    {
        FileStreamResult fsr = null;
        string excelPath = @"C:\Temp\Excel.xls";
        try
        {
    
            var filename = Path.GetFileName(excelPath);
            Stream tempFileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            fsr = new FileStreamResult(tempFileStream, MimeHelper.GetMimeType(filename));
        }
        catch (Exception e)
        {
            Log.Error(e, "Failed to read: {FILE}", excelPath);
            return fsr;
        }
    
        return fsr;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-10
      • 2012-11-30
      • 2012-12-25
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2019-01-08
      相关资源
      最近更新 更多