user3817601
user3817601

Reputation: 13

Consuming ASP.NET Web API from classic ASP to download file

I have a legacy Classic ASP application that serves as a repository for a bunch of files available for download. I would prefer to not rewrite the entire application at this time but instead want to pull out the file download logic into an ASP.NET Web API.

I have created the service and when I hit the service via my browser the download starts just fine with the hardcoded filename I have in the app and I am able to save. I am having trouble consuming the service from my asp app however. If I modify the code below to just return a JSON value, I am able to return the value to the asp app. So I at least know there is communication happening. Just not sure how to handle a file download.

HERE IS MY SERVICE LOGIC:

   // GET api/values/5
    public HttpResponseMessage Get(int id)
    {
        //return "value";
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        string filePath = "H:/Temp/Filename.exe";

        MemoryStream memoryStream = new MemoryStream();

        FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        byte[] bytes = new byte[file.Length];

        file.Read(bytes, 0, (int)file.Length);

        memoryStream.Write(bytes, 0, (int)file.Length);

        file.Close();

        httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());

        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Filename.exe" };

        httpResponseMessage.StatusCode = HttpStatusCode.OK;

        return httpResponseMessage;

    }

HERE IS A SUBSET OF MY CLASSIC ASP LOGIC:

Response.Addheader "Content-Disposition", "attachment; filename=Filename.exe"

Response.ContentType = "application/octet-stream" 'EXE

Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")

HttpReq.open "GET", "http://webservice/api/values/1", False

HttpReq.send

Response.BinaryWrite HttpReq.responsestream  

Upvotes: 0

Views: 1530

Answers (1)

Steve Newton
Steve Newton

Reputation: 1078

What about something like:

Set HttpReq = Server.CreateObject("ADODB.Stream")
HttpReq.open "GET", "http://webservice/api/values/1", False
Response.BinaryWrite HttpReq.read

Upvotes: 1

Related Questions