0

In my one of .Net Framework 4.5 project, i had been creating response (file download) as following

.Net Framework 4.5 version

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

As you can see i am adding cookie, Header ContentType etc.

Here is my ported .Net Core version.

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", "");
    }
}

Issue:

1- I could not find the way to set ContentDisposition

2- There is no Response.Content (I could not find Response.Content = new StreamContent(stream) in .Net Core.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
simbada
  • 940
  • 4
  • 24
  • 43

1 Answers1

0

I used this way and didn't have to care about 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;
}
Benjamin Schäublin
  • 1,526
  • 1
  • 16
  • 26