通过处理程序下载 WebApi 文件

WebApi file download via handler

我正在使用 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 吗?按路由属性?

来自 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 类型,实际上您不需要为此设置特定的处理程序。

PushStreamContent 发送 zip 文件的示例

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;