AspNetCore下载(导出)文件

时间:2017-08-19 11:34:46

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

.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(流)。

1 个答案:

答案 0 :(得分:0)

我用这种方式并没有关心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;
}