使用ASP.NET Web API从经典ASP下载文件
本文关键字:ASP 经典 下载 文件 API NET Web 使用 | 更新日期: 2023-09-27 18:12:06
我有一个传统的经典ASP应用程序,它作为一堆文件的存储库可供下载。此时我不希望重写整个应用程序,而是希望将文件下载逻辑提取到ASP中。. NET Web API。
我已经创建了服务,当我通过浏览器点击服务时,下载开始很好,我在应用程序中有硬编码的文件名,我能够保存。我有麻烦从我的asp应用程序消费服务。如果我修改下面的代码,只是返回一个JSON值,我能够返回值到asp应用程序。所以我至少知道有通信发生。只是不知道如何处理文件下载。
这是我的服务逻辑:
// 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;
}
这是我的经典ASP逻辑的一个子集:
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
Set HttpReq = Server.CreateObject("ADODB.Stream")
HttpReq.open "GET", "http://webservice/api/values/1", False
Response.BinaryWrite HttpReq.read