gpt4 book ai didi

c# - 通过处理程序下载 WebApi 文件

转载 作者:行者123 更新时间:2023-11-30 18:22:04 28 4
gpt4 key购买 nike

我正在使用 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>

关于c# - 通过处理程序下载 WebApi 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480934/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com