当我使用 web api 调用下载文件时,我可以轻松下载文件。唯一的问题是在我的错误日志中发送了HTTP 标头后,我得到服务器无法设置状态。对不起,如果这可能是一个重复的问题,但这里的答案都没有帮助我。
<a href="/api/DownloadDocumentById?documentId=<%=doc.Id %>" download>
<i class="fa fa-download text-primary"></i>
</a>
<HttpGet>
<ActionName("DownloadDocumentById")>
Public Function DownloadDocumentById(documentId As Integer)
Dim document = xxxxxxxx
Dim context = HttpContext.Current
context.Response.ContentType = document.Type
context.Response.OutputStream.Write(document.Content, 0, document.Size)
context.Response.AddHeader("Content-Disposition", Baselib.FormatContentDispositionHeader($"{document.Name}"))
context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString())
context.Response.Flush()
context.Response.End()
Return HttpStatusCode.OK // Have also tried to create a sub without returning a value
End Function
如前所述,我可以轻松下载该文档,但是在发送 HTTP 标头错误后,IIS 日志服务器仍无法设置状态。再次抱歉这是一个重复的问题。希望可以有人帮帮我。
首先,我认为您应该在开始编写实际输出/内容之前添加所有标题。使用缓冲流(这是我将要建议的),这应该没有区别,并且主要是语义上的,但是由于应该在写入内容之前添加标题(内容总是最后),因此可以避免类似的问题如果您决定使用未缓冲的流,则将来。
因此,我建议您相应地重新排序代码:
context.Response.ContentType = document.Type
context.Response.AddHeader("Content-Disposition", Baselib.FormatContentDispositionHeader($"{document.Name}"))
context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString())
context.Response.OutputStream.Write(document.Content, 0, document.Size)
现在,如果您使用无缓冲流,内容将在您调用时立即发送到客户端OutputStream.Write()
,因此为了之后设置 HTTP 结果,您需要确保整个响应都已缓冲,以便在您的内部响应之前不会发送它请求(动作和控制器)已完成执行。这可以通过在输出任何内容之前设置Response.BufferOutput
为来完成True
:
context.Response.BufferOutput = True
context.Response.ContentType = document.Type
'The rest of the code...
最后,您需要删除对Response.Flush()
和的调用,Response.End()
因为它们过早地清空缓冲区并将所有内容写入客户端,甚至在您返回状态代码之前。
新代码:
(...)
context.Response.BufferOutput = True
context.Response.ContentType = document.Type
context.Response.AddHeader("Content-Disposition", Baselib.FormatContentDispositionHeader($"{document.Name}"))
context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString())
Return HttpStatusCode.OK
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句