Download file from REST service in C#

Viewed 11393

I am trying to save a file to the client's machine. I want to require the client to pick the location of the download.

I have endpoint of the REST service which returns the file to be downloaded. I am trying to set up the code to download the file thats returned from the service with save as dialog.

            var Url = "https://randomaddresss/v5/invoices/{" + InvoicesId + "}/getpdfbyid";

            HttpResponse response = HttpContext.Current.Response;

            response.ClearContent();
            response.Clear();

            response.ContentType = "application/pdf";
            response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;");

            response.TransmitFile(Url);

            response.Flush();
            response.End();

The error thats returned is on the line response.TransmitFile(Url); :

'https:/randomaddresss/v5/invoices/2131231231231312/getpdfbyid' is not a valid virtual path.

2 Answers

HttpResponse.TransmitFile expects a file path, not a URL.

You will need to download the file first, then write to the response stream.

Here's an example using HttpClient:

using var invoiceResponse = await httpClient.GetAsync(Url);
using var invoiceStream = await invoiceResponse.Content.ReadAsStreamAsync();

invoiceStream.CopyTo(response.OutputStream);

response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;");

JS:

function downloadPdfInvoice(iId) {
$.ajax({
    url: '/api/DownloadInvoice?Invoice=' + iId,
    type: 'get',
    success: function (response, status) {
        if (response) {

            var link = document.createElement('a');
       
            link.href = "data:application/octet-stream;base64," + response.Data;
            link.target = '_blank';
            link.download = iId + '.pdf';
            link.click();

        }
    },
});

}

CS:

    [HttpGet]
    public ApiResponse DownloadInvoiceAsync(string InvoicesId)
    {
        try
        {
            String Url = "https://test/{" + InvoicesId + "}/getpdfinvoice";

            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);

            var resp = fileReq.GetResponse();
       
            Stream input = resp.GetResponseStream();
            byte[] data = input.ReadAsBytes();

            return new ApiResponse(true, "Downloadet til skrivebordet.", data);
        }
        catch (Exception ex)
        {
            Logger.Warn(MethodBase.GetCurrentMethod().DeclaringType,
                string.Format("DownloadInvoice Exception {0}", ex.Message));
            throw ex;
        }
    }
Related