'Returning PDF as FileContentResult from byte array produces invalid file

I need a link for downloading or viewing a pdf in the browser. I tried almost every solution but after downloading the pdf file, the file seems broken.

My Controller:

public ActionResult DownloadKalite(Guid oid)
{
    string contentType = "application/pdf";
    List<KaliteDokumanlari> kalite = db.KaliteDokumanlari.Where(a => a.Oid == oid && a.GCRecord == null).ToList();

    string filename = kalite.Select(y => y.FileData.FileName).FirstOrDefault();
    byte[] filearray = kalite.Select(y => y.FileData.Content).FirstOrDefault();
     
    return File(filearray, contentType, filename);
}

My download link in view:

<div id="panel3d">
    @foreach (var doc in item.KaliteDokumanlari)
    {
        <div>
           @Html.ActionLink(doc.FileData.FileName, "DownloadKalite", new { @oid = doc.Oid })
        </div>
    }
</div>

After download pdf seems ok PDF Error



Solution 1:[1]

Try getting the byte into a MemoryStream

var pdfStream= new MemoryStream();    
pdfStream.Write(filearray , 0, filearray .Length);  
pdfStream.Position = 0; 

return File(pdfStream, contentType, filename);

If this does not work store the pdf as base64 string to avoid byte loss.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vbouzoukos