I am trying to return a pdf file from my REST API and have added a ReportController to my collection of controllers as follows.
public class ReportController : ApiController
{
public HttpResponseMessage Get(int id)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
string fileName = id.ToString();
MemoryStream memoryStream = GetStreamFromBlob(fileName);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
}
The other controllers all work fine, however this is the first that has been set to return a HttpResponseMessage rather than a serializable object or collection of objects.
However I am having difficulty consuming this from the client end. Have tried a number of versions of code to do this however the controller code never gets hit, and there seem to be few complete examples of a successful way to call this. The following is my current version:-
public async Task<string> GetPdfFile(int id)
{
string fileName = string.Format("C:\\Code\\PDF_Client\\{0}.pdf", id);
using (HttpClient proxy = new HttpClient())
{
string url = string.Format("http://localhost:10056/api/report/{0}", id);
HttpResponseMessage reportResponse = await proxy.GetAsync(url); //****
byte[] b = await reportResponse.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes(fileName, b);
}
return fileName;
}
However the line ****
fails with the message No connection could be made because the target machine actively refused it 127.0.0.1:10056
.
As I say, other controllers at http://localhost:10056/api/
work fine.
Is this the correct way to GET a file from a WEBAPI server method?
Do you have any advice as to other areas of the code that could be better such as use of await/async, or better ways for the controller to return a file?