I am trying to configure a web api service that looks for a .pdf file in a directory and returns the file if it is found.
Controller
public class ProductsController : ApiController { [HttpPost] public HttpResponseMessage Post([FromBody]string certificateId) { string fileName = certificateId + ".pdf"; var path = @"C:\Certificates\20487A" + fileName;
I call the service with the following code
private void GetCertQueryResponse(string url, string serial) { string encodedParameters = "certificateId=" + serial.Replace(" ", ""); HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.Method = "POST"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.AllowAutoRedirect = false; byte[] bytedata = Encoding.UTF8.GetBytes(encodedParameters); httpRequest.ContentLength = bytedata.Length; Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytedata, 0, bytedata.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { byte[] bytes = null; using (Stream stream = response.GetResponseStream()) using (MemoryStream ms = new MemoryStream()) { int count = 0; do { byte[] buf = new byte[1024]; count = stream.Read(buf, 0, 1024); ms.Write(buf, 0, count); } while (stream.CanRead && count > 0); ms.Position = 0; bytes = ms.ToArray(); } var filename = serial + ".pdf"; Response.ContentType = "application/pdf"; Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + filename + "\""); Response.BinaryWrite(bytes); } }
This seems to work in the sense that the download file dialog is displayed with the correct name and file size, etc., but the download takes only a couple of seconds (when the file size is> 30 MB) and the files are damaged when I try to open them .
Any ideas what I'm doing wrong?
source share