WebApi文件通过处理程序下载

时间:2015-12-27 13:35:11

标签: c# asp.net-web-api asp.net-web-api2

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

2 个答案:

答案 0 :(得分:0)

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

并通过web.config可以路由到地方:

ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("country", countryNameFromSharedPreference);
installation.saveInBackground();

答案 1 :(得分:0)

如果我理解你的问题,你会尝试从服务器向用户发送一些内容。如果是这样,请尝试使用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;
相关问题