通过处理程序下载WebApi文件

本文关键字:WebApi 文件 程序下载 处理 | 更新日期: 2023-09-27 18:28:13

我正在使用WebAPI下载这样的.pdf文件:

[HttpGet]
public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
{
HttpResponseMessage result = null;
try
{
    MyService service = new MyService();
    var bytes = await service.DownloadFileAsync(id);
    if (bytes != null)
    {
        result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
    }
    else
    {
        result = new HttpResponseMessage(HttpStatusCode.NotFound);
    }
}
catch (Exception ex)
{
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
}
return result;
}
private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
   // result.Content = new ByteArrayContent(bytes);
result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
if (attachment)
{
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Content.Headers.ContentLength = bytes.Length;
return result;
}

现在,我看到它冻结了我的网站,所以我想更改它,并通过处理程序下载一个pdf文件,是否可以在客户端进行任何更改的情况下路由到IHttpHandler?按路由属性?

通过处理程序下载WebApi文件

http://www.fsmpi.uni-bayreuth.de/~dun3/archives/task-based ihttpasynchandler/532.html帮助我实现异步处理程序。

通过web.config可以路由到以下位置:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"></modules>
  <handlers>  
    <add
       name="DownFile"
       path="/api/downloads/MyDownload.axd"
       type="MyProject.WebApi.Handlers.MyDownloadAsyncHandler, MyProject.WebApi"
       verb="GET"/>
  </handlers>
</system.webServer>

如果我理解您的问题,您可以尝试从服务器向用户发送一些内容。如果是这样,请尝试使用PushStreamContent类型,实际上您不需要为此指定特定的处理程序。

发送zip文件的PushStreamContent示例

ZipFile zip = new ZipFile()
// Do something with 'zip'
var pushStreamContent = new PushStreamContent((stream, content, context) =>
{
    zip.Save(stream);
    stream.Close();
}, "application/zip");
HttpResponseMessage response = new HttpResponseMessage
{
    Content = pushStreamContent,
    StatusCode = HttpStatusCode.OK
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "fileName"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;